static variable link error

后端 未结 3 2007
名媛妹妹
名媛妹妹 2020-11-22 08:27

I\'m writing C++ code on a mac. Why do I get this error when compiling?:

Undefined symbols for architecture i386: \"Log::theString\", referenced f

相关标签:
3条回答
  • 2020-11-22 08:41

    You must define the statics in the cpp file.

    Log.cpp

    #include "Log.h"
    #include <ostream>
    
    string Log::theString;  // <---- define static here
    
    void Log::method(string arg){
        theString = "hola";
        cout   << theString << endl; 
    }
    

    You should also remove using namespace std; from the header. Get into the habit while you still can. This will pollute the global namespace with std wherever you include the header.

    0 讨论(0)
  • 2020-11-22 08:44

    In C++17, there is an easier solution using inline variables:

    class Log{
    public:
        static void method(string arg);
    private:
        inline static string theString;
    };
    

    This is a definition, not just a declaration and similar to inline functions, multiple identical definitions in different translation units do not violate ODR. There is no longer any need to pick a favourite .cpp file for the definition.

    0 讨论(0)
  • 2020-11-22 08:58

    You declared static string theString;, but haven't defined it.

    Include

    string Log::theString;
    

    to your cpp file

    0 讨论(0)
提交回复
热议问题