静态变量链接错误

sub*_*ero 63 c++ xcode static-methods clang static-libraries

我在mac上编写C++代码.编译时为什么会出现此错误?:

体系结构i386的未定义符号:"Log :: theString",引用自:libTest.a中的Log :: method(std :: string)(Log.o)ld:未找到体系结构i386 clang的符号:错误:链接器命令失败,退出代码为1(使用-v查看调用)

不确定我的代码是否错误或者我必须向Xcode添加其他标志.我当前的XCode配置是"静态库"项目的默认配置.

我的代码:

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

#include <iostream>
#include <string>

using namespace std;

class Log{
public:
    static void method(string arg);
private:
    static string theString ;
};
Run Code Online (Sandbox Code Playgroud)

Log.cpp ----

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

void Log::method(string arg){
    theString = "hola";
    cout   << theString << endl; 
}
Run Code Online (Sandbox Code Playgroud)

我用测试代码调用'方法',这样:'Log :: method("asd"):'

谢谢你的帮助.

Luc*_*ore 81

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

Log.cpp

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

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

void Log::method(string arg){
    theString = "hola";
    cout   << theString << endl; 
}
Run Code Online (Sandbox Code Playgroud)

您还应该using namespace std;从标题中删除.在你还可以的时候养成这个习惯.std无论您在哪里包含标头,都会污染全局命名空间.

  • 也许更好的术语是它为字符串分配空间. (9认同)

Lol*_*4t0 16

你声明了static string theString;,但没有定义它.

包括

string Log::theString;
Run Code Online (Sandbox Code Playgroud)

到你的cpp文件