我试图在c++中定义一些静态常量字符串,并从不同的文件中引用它们。
到目前为止,我是这样设置信息的:
structClass.h
namespace test {
typedef struct customstructure{
static const std::string stringA;
} customstructure;
}
structClass.cpp
namespace test {
static const std::string customstructure::stringA = "This is String A";
}
现在我想知道如何在第三个文件中调用它?
execute.cpp
void printStringA(){
printf("stringA is: %s", test::customstructure::stringA.c_str());
}
给了我一个编译错误,说:
对test::customstructure::stringA的未定义引用
在此代码中:
namespace test {
static const std::string customstructure::stringA = "This is String A";
}
删除单词static
。事实上,这是一个错误,你的编译器应该给出一个更有用的错误信息(尽管我认为"未定义的引用"符合"诊断"的要求)。
标准参考:[class.static.data]#5
表示静态数据成员具有外部链接,但是在定义中使用关键字static
将指定内部链接。