静态变量链接错误

79

我正使用Mac编写C++代码。为什么在编译时会出现以下错误?:

符号未定义(针对i386架构):“Log::theString”,出现在: Log::method(std::string) in libTest.a(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 ;
};

日志.cpp ----

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

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

我正在测试代码中调用'method',方式如下:'Log::method("asd"):'

感谢您的帮助。

2个回答

109

你必须在 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污染全局命名空间。


更倾向于初始化而不是定义,没问题吧(只是问问)? - Vyktor
11
也许更合适的术语是它为字符串分配空间。 - btown
非常感谢您,您帮了我很多! - JavaRunner
1
在头文件中使用 using namespace *; 的观点很好。如果你能早点改掉这个习惯会更容易些。 - Benjineer
1
只需将 using namespace std; 放在你自己的命名空间声明内即可 :P namespace your_custom_namespace { using namespace std; } - Pellet

23

你声明了 static string theString;,但是还没有定义它。

包括

string Log::theString;

将代码添加到您的 cpp 文件中


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接