"Undefined symbols" with static fields



  • Hi guys!

    With this code:

    #include <QString>
    #include <QDir>
    
    class Repository
    {
    public:
        static void Create() {
            BaseDirectory = Require("/Library/Application Support/myapp");
            LogDirectory = Require(BaseDirectory, "Logs");
        }
        static QString GetBaseDirectory() {
            return BaseDirectory;
        }
    private:
        static QString BaseDirectory;
        static QString LogDirectory;
    
        static QString Require(QString path){
            QDir dir(path);
            if (!dir.exists(path)) {
                dir.mkpath(path);
            }
            return path;
        }
        static QString Require(QString basePath, QString relPath){
            QString path = basePath + QDir::separator() + relPath;
            Require(path);
            return path;
        }
    };
    

    used here:

    #include "Repository.h"
    int main(int argc, char *argv[])
    {    
       Repository::Create();
    }
    

    i get this linker error:

    Undefined symbols for architecture x86_64:
      "Repository::LogDirectory", referenced from:
          Repository::Create() in main.o
      "Repository::BaseDirectory", referenced from:
          Repository::Create() in main.o
    ld: symbol(s) not found for architecture x86_64
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    

    Clang on MAC!
    What's the problem??????
    :-(



  • You forgot to define the static members.
    Something like

    QString Repository::BaseDirectory;
    QString Repository::LogDirectory;
    

    in cpp file



  • woah you have saved my day!!!



  • @mcosta is possible to define the static members in .h file?



  • You have to be sure that static objects are initialized once. If you include into header file they will be initialized every time you include the header file. You can do this using special include guards but IMO is a very bad code style.

    I suggest to create a cpp file (or you can do it in main.cpp)


Log in to reply
 

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