Important: Please read the Qt Code of Conduct -

Static members in static library

  • I have a QWidget project with several sub-projects as static libraries.
    One of them contains s tatic member (I tried also with a static function).

    class myClass : public QObject
        explicit myClass(QObject *parent = 0);
        static int myStaticMember;

    The library compiles fine (i.e. libmyClass is generated).
    In another static library of my project I want to use myStaticMember.
    Thus I imported the library in the project file:

    LIBS += -L$$OUT_PWD/../myClass/ -lmyClass
    INCLUDEPATH += $$PWD/../myClass
    DEPENDPATH += $$PWD/../myClass
    PRE_TARGETDEPS += $$OUT_PWD/../myClass/libmyClass.a

    Also this library compiles fine, and contains a call to that member:

    #include "myClass.h"
    qDebug() << myClass::myStaticMember;

    The problem rises when I build the whole project. I get the following error:

    myClass/myClass.cpp:15: error: undefined reference to `myClass::myStaticMember'

    Another weird thing is that the line pointed by the error is few lines below the actual call to the myStaticMember - and it isn't related at all (I declare a QTimer...).

    Why the linker cannot find the member?

  • Moderators

    What platform are you running, windows or *nix? Do you have that static member defined in the cpp file for myClass?

  • @kshegunov Linux. mmm, no, it's just a public variable. What do you mean with "define in the cpp file"?

  • Moderators

    @Mark81 said:
    Having this:

    class myClass
         static int myStaticMember;

    You should also do in the cpp file (usually on top):

    int myClass::myStaticMember = 12345; //< Definition and initialization

    On Linux the archive (static lib) is not checked for pretty much anything before linking, so you can have the *.a generated and still fail to link.

  • @kshegunov Ok, I thought is was optional, not mandatory. My fault. Now it compiles fine, thanks.

  • Moderators

    No problem.