【发布时间】:2011-05-11 18:47:11
【问题描述】:
我似乎无法使用extern 从命名空间内引用外部定义的变量。它在全局范围内工作,但是一旦将名称空间投入其中,它就无法链接。
我的常量文件如下所示:
StringConstants.cpp
#include "MyString.h"
MyString test1("string1");
MyString test2("string2");
主程序如下所示:
main.cpp
#include <stdio.h>
#include "MyString.h"
extern MyString test1;
namespace {
extern MyString test2;
}
int main(void) {
printf("%s\n", test1.Str());
printf("%s\n", test2.Str());
}
我在 GCC 和 Visual Studio 中都遇到了类似的错误:
gcc main.o StringConstants.o -o main
main.o:main.cpp:(.text+0x49): undefined reference to `(anonymous namespace)::test2'
collect2: ld returned 1 exit status
1>Linking...
1>main.obj : error LNK2001: unresolved external symbol "class MyString `anonymous namespace'::test2" (?test2@?A0x0df4aa01@@3VMyString@@A)
1>C:\p4\namespace_repro\namespace_repro2\Debug\namespace_repro2.exe : fatal error LNK1120: 1 unresolved externals
我尝试限定对 test2 (extern MyString ::test2) 的引用,但它只是认为 test2 是 MyString 的静态成员。命名命名空间的行为与匿名命名空间没有区别。出于各种原因,我们不想删除命名空间或将 externs 放在命名空间之外。
为了完整起见,这是其他文件:
MyString.h
class MyString {
public:
MyString(const char* str): mStr(str) {};
const char* Str() const { return mStr; }
private:
const char* mStr;
};
Makefile
CC=gcc
CFLAGS=-Wall
main: StringConstants.o main.o
该系统的目标是所有常量都定义在一个文件中,并且它们在链接时被解析,而不是在标题中。上面的代码似乎可以工作,但由于它被两个不同的链接器拒绝,我对 C++ 的理解似乎还不够好。关于如何让它工作的建议,除了将外部放在命名空间之外?
【问题讨论】:
标签: c++ namespaces linker constants extern