static variable link error

放肆的年华 提交于 2019-11-25 23:37:54

问题


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

Undefined symbols for architecture i386: \"Log::theString\", referenced from: Log::method(std::string) in libTest.a(Log.o) ld: symbol(s) not found for architecture i386 clang: error: linker command failed with exit code 1 (use -v to see invocation)

Not sure if my code is wrong or I have to add additional flags to Xcode. My current XCode configurations are the default ones for a \'static library\' project.

My code:

Log.h------------

#include <iostream>
#include <string>

using namespace std;

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

Log.cpp ----

#include \"Log.h\"
#include <ostream>

void Log::method(string arg){
    theString = \"hola\";
    cout   << theString << endl; 
}

I\'m calling the \'method\' from a test code, in this way: \'Log::method(\"asd\"):\'

thanks for your help.


回答1:


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.




回答2:


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

Include

string Log::theString;

to your cpp file



来源:https://stackoverflow.com/questions/9282354/static-variable-link-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!