2012-02-14 48 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文件