Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Problems with extern int



  • I started in python and have migrated to C++ in Qt. I am having problems with variables inside and outside of classes. I've researched everywhere and implemented everything I've found but no progress.

    I slashed out the sections of code that shouldn't have any bearing on the code that is related to my problem.

    in game.ccp

    game::game(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::game)
    {
    ui->setupUi(this);
    int status = 0;
    //int salary = 200;
    //QString tot_tokens = QString::number(salary);
    //ui->tot_tkn2->setText(tot_tokens);
    }
    game::~game()
    {
    delete ui;
    }
    void game::on_wagerSet_clicked()
    {
    //QString bet_amount = ui->wagerAmt->text();
    //ui->tot_tkn->setText(bet_amount);
    extern int status;
    if( status==0){
        ui->tot_tkn2->setText("10");
    }
    }
    

    I am wanting to track and execute certain actions that are dependent on the status of the poker simulator and changes every time the player presses the submit wager button (excess information). I believe my problem has something to do with the extern phrase used but I am unsure


  • Qt Champions 2019

    'extern int' only tells the compiler that there is a variable somewhere else in your code but nothing more. So you need to define it somewhere otherwise you will get a linker error (when this is the problem you have - you did not tell us) - Basic C problem.


  • Moderators

    @ConnorFord said in Problems with extern int:

    game::game(QWidget *parent) :
        QDialog(parent),
        ui(new Ui::game)
    {
        ui->setupUi(this);
        int status = 0;
    }
    

    Above, status is a local variable which only exists inside your constructor function, game::game(). As soon as a function returns, all of its local variables are destroyed.

    From your code snippet, it looks like you want status to be a variable that is linked to your game object and be accessible by other class methods like game::on_wagerSet_clicked() (like creating a Python property called "status"), is that right? If so, you should declare status as a member variable of your game class.

    Note: It is not appropriate to use extern here.

    class game : public QWidget {
    
        Q_OBJECT
    
    public:
        game(QWidget *parent = nullptr);
        on_wagerSet_clicked();
    
        int status() const { return m_status; } // This is a public getter for m_status
    
    private:
        int m_status; // This is a declaration of a private member variable
    }
    

Log in to reply