C++ 静态变量链接错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9282354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
static variable link error
提问by subzero
I'm writing C++ code on a mac. Why do I get this error when compiling?:
我正在 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)
架构 i386 的未定义符号:“Log::theString”,引用自:Log::method(std::string) in libTest.a(Log.o) ld: 找不到架构 i386 clang 的符号:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)
Not sure if my code is wrong or I have to add additional flags to Xcode. My current XCode configurations are the default ones for a 'static library' project.
不确定我的代码是否有误,或者我必须向 Xcode 添加其他标志。我当前的 XCode 配置是“静态库”项目的默认配置。
My code:
我的代码:
Log.h------------
日志.h------------
#include <iostream>
#include <string>
using namespace std;
class Log{
public:
static void method(string arg);
private:
static string theString ;
};
Log.cpp ----
日志.cpp ----
#include "Log.h"
#include <ostream>
void Log::method(string arg){
theString = "hola";
cout << theString << endl;
}
I'm calling the 'method' from a test code, in this way: 'Log::method("asd"):'
我从测试代码中调用“方法”,以这种方式: 'Log::method("asd"):'
thanks for your help.
谢谢你的帮助。
回答by Luchian Grigore
You must define the statics in the cpp
file.
您必须在cpp
文件中定义静态。
Log.cpp
日志文件
#include "Log.h"
#include <ostream>
string Log::theString; // <---- define static here
void Log::method(string arg){
theString = "hola";
cout << theString << endl;
}
You should also remove using namespace std;
from the header. Get into the habit while you still can. This will pollute the global namespace with std
wherever you include the header.
您还应该using namespace std;
从标题中删除。在你还可以的时候养成这个习惯。std
无论您在何处包含标题,这都会污染全局命名空间。
回答by Lol4t0
You declared static string theString;
, but haven't defined it.
您声明了static string theString;
,但尚未定义它。
Include
包括
string Log::theString;
to your cpp
file
到你的cpp
文件