微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 静态变量链接错误

我在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; 
}

我用测试代码调用方法’,这样:
登录::方法( “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; 
}

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐