我似乎无法使用命名空间引用外部定义的变量extern.它在全局范围内工作,但只要在其中抛出命名空间,就无法链接.
我的常量文件看起来像:
StringConstants.cpp
#include "MyString.h"
MyString test1("string1");
MyString test2("string2");
Run Code Online (Sandbox Code Playgroud)
主程序如下所示:
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());
}
Run Code Online (Sandbox Code Playgroud)
我在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
Run Code Online (Sandbox Code Playgroud)
我尝试限定对test2(extern MyString ::test2)的引用,但它只是认为test2是MyString的静态成员.命名命名空间的行为与匿名命名空间的行为不同.由于各种原因,我们不希望删除命名空间或将外部函数放在命名空间之外.
这是其他文件,为了完整性: …