Using static variables in programs

  • Hi,

    Please take a look at this shortened version of the real app. I built this program just to follow and solve the issue in a simpler way. How to use a static variable. well, of course, my purpose is to prevent various objects to have a copy of that.

    #ifndef TEST1_H
    #define TEST1_H
    #include <QDialog>
    class QLineEdit;
    class QPushButton;
    class test1 : public QDialog
        test1(QWidget* parent = 0);
    private slots:
        void show_clicked();
        static int i;
        QLineEdit* line;
        QPushButton* show_number;
        QPushButton* quit;
    #endif // TEST1_H
    #include <QtWidgets>
    #include "test1.h"
    test1::test1(QWidget* parent)
        : QDialog(parent)
      i = 5;
     line = new QLineEdit;
      show_number = new QPushButton(tr("show"));
      quit = new QPushButton(tr("Quit"));
      connect(show_number, SIGNAL(clicked(bool)),
              this, SLOT(show_clicked()));
      connect(quit, SIGNAL(clicked(bool)), this, SLOT(close));
      QVBoxLayout* layout = new QVBoxLayout();
    void test1::show_clicked()
    #include "test1.h"
    int main(int argc, char* argv[])
        QApplication app(argc, argv);
        test1* t1 = new test1;
        return app.exec();

    When I run the code I get 3 errors:

    error: undefined reference to `test1::i'

    error: undefined reference to `test1::i'

    error: error: ld returned 1 exit status

  • Hi @tomy ,
    you have to define them "outside" again:

    Add in your .cpp:

    int test1::i = 0;
    test1::test1(QWidget* parent)
        : QDialog(parent) { ... }

  • This post is deleted!

  • @beecksche
    Thank you. It was solved.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.