【发布时间】:2014-05-22 05:41:45
【问题描述】:
我已经为嵌入式系统编写了一些 C++ 代码,它的工作原理就像一个魅力。当前任务是在 PC 上模拟此设备的行为。必须移植一些代码:对于第一次测试,我使用的是 mingw (g++),而嵌入式系统是 STM32 并使用 KEIL µVision 工具链。
我遇到了一个与函数行为无关的问题,而不是编译器特定的怪异问题。我在匿名命名空间中定义了 2 个类,因为它们包含在整个项目中。现在在嵌入式设备上编译和运行没有问题。 g++ 抱怨一个未定义的引用!
当我删除围绕类的匿名命名空间时,它会编译并运行!但为什么?下面是一些重现这种情况的示例代码: main.cpp:
#include "notmain.h"
#include "theclass.h"
A *ourA=NULL;
int main()
{
theA = new A();
theA->dostuff(1024);
sunshine sun;
sun.Init();
}
notmain.cpp:
#include "notmain.h"
#include "theclass.h"
void sunshine::Init()
{
theA->dostuff(127);
}
notmain.h:
#ifndef NOTMAIN_H_
#define NOTMAIN_H_
class sunshine
{
public:
void Init();
};
#endif
theclass.h:
#ifndef THECLASS_H_
#define THECLASS_H_
#include <stdio.h>
#define theA ourA
namespace
{
class A
{
public:
void dostuff(int b)
{
a = b;
printf("Hello: %d\n",a);
}
private:
int a;
};
}
extern A *ourA;
#endif
编译器/链接器输出:
09:09:57 ** Testo项目配置调试的增量构建**
信息:内部构建器用于构建
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o main.o "..\main.cpp"
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o notmain.o "..\notmain.cpp"
g++ -o Testo.exe notmain.o main.o
notmain.o:在函数ZN8sunshine4InitEv':
D:\Projekte\Testo\Debug/../notmain.cpp:6: undefined reference toourA'
collect2.exe:错误:ld 返回 1 个退出状态
09:09:57 Build Finished (took 702ms)
删除该命名空间可以解决问题,但为什么它可以在 KEIL 中编译、链接和工作?谁能给我解释一下?
【问题讨论】:
-
不要在头文件中使用匿名命名空间
-
在标头中使用未命名的命名空间有什么好处? +1 顺便提一个写得很好的问题。
-
@OMGtechy:clambake 的推理是“一个匿名命名空间,因为它们包含在整个项目中”;但它是有缺陷的——匿名命名空间正好相反。