静态变量链接错误 [英] static variable link error
问题描述
我在Mac上编写C ++代码。为什么编译时会出现这个错误:
架构i386的未定义符号:Log :: theString,
从:
libTest.a(Log.o)中的Log ::方法(std :: string)ld:没有为架构i386找到符号:clon:error:linker命令失败,
退出代码1(使用-v查看调用)
不知道我的代码是否错误或者我必须向Xcode添加额外的标志。我目前的XCode配置是静态库项目的默认配置。
我的代码:
.h ------------
#include< iostream>
#include< string>
using namespace std;
class Log {
public:
static void method(string arg);
private:
static string theString;
};
Log.cpp ----
#includeLog.h
#include< ostream>
void Log :: method(string arg){
theString =hola;
cout<< theString< endl;
}
我从测试代码调用'method' :
'Log :: method(asd):'
感谢您的帮助。
Log.cpp
#includeLog.h
#include< ostream>
string Log :: theString; //< ---- define static here
void Log :: method(string arg){
theString =hola;
cout<< theString< endl;
}
您还应该使用namespace std; 从头。在你还可以的时候养成习惯。这将使用 std
来污染全局命名空间,无论你包含头。
I'm writing C++ code on a mac. Why do I get this error when compiling?:
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)
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.
My code:
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;
}
I'm calling the 'method' from a test code, in this way: 'Log::method("asd"):'
thanks for your help.
You must define the statics in the cpp
file.
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.
这篇关于静态变量链接错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!