2012-02-14 22 views
53

私はMacにC++コードを書いています。私のコードが間違っているか、私はXcodeのに追加のフラグを追加する必要があればわからない静的変数リンクエラー

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設定は、 'スタティックライブラリ'プロジェクトのデフォルト設定です。

マイコード:

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

string Log::theString; 

を含めます。参照される他の質問は本質的に非常に一般的で、私のMac特有の問題を解決するのには役に立たなかったでしょう。 – Adam

答えて

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

* define *の代わりに*を初期化する*、いいえ(ただ質問する)? – Vyktor

+0

@Vyktor私は両方が受け入れられると思います。 –

+9

おそらくもっと良い言葉でさえ、文字列にスペースを割り当てます。 – btown

12

static string theString;と宣言しましたが、定義していません。

は、私はこれが重複質問であることを同意しないあなたのcppファイル