2012-02-14 79 views
53

我在Mac上编写C++代码。为什么?:编译静态变量链接错误

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)

不知道如果我的代码是错误的,或者有额外的标志添加到Xcode的,当我得到这个错误。我当前的XCode配置是“静态库”项目的默认配置。

我的代码:

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; 
} 

我从测试代码调用'方法',通过这种方式: 'Log :: method(“asd”):'

感谢您的帮助。

+4

我不同意,这是一个重复的问题。引用的另一个问题本质上是非常普遍的,并不会帮助我解决我的mac特定问题。 – Adam 2016-08-29 16:09:56

回答

65

您必须在cpp文件中定义静态。

Log.cpp

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

string Log::theString; // <---- define static here 

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

你也应该从头部取出using namespace std;。在你仍然可以的时候养成习惯。无论您在何处添加标题,这都会污染全局名称空间std

+0

相反*初始化*而不是*定义*,否(只是问)? – Vyktor 2012-02-14 18:49:44

+0

@Vyktor我认为两人都被接受。 – 2012-02-14 18:51:01

+9

也许更好的一点是它会为字符串分配空间。 – btown 2012-02-14 19:55:46

12

您声明static string theString;,但尚未定义它。

包括

string Log::theString; 

cpp文件