静态变量链接错误

static variable link error

本文关键字:错误 链接 变量 静态      更新时间:2023-10-16

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

体系结构i386的未定义符号:"日志:字符串",引用自:在libTest.a(Log.o)ld:symbol中找不到体系结构i386的Log::方法(std::string)clang:error:链接器命令失败退出代码1(使用-v查看调用)

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

我的代码:

日志----------------

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

我从测试代码中调用"方法",方法如下:'日志::方法("asd"):'

谢谢你的帮助。

您必须在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污染全局命名空间,无论您在哪里包含头。

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

包括

string Log::theString;

到您的cpp文件

相关文章: