【发布时间】:2014-03-31 15:25:33
【问题描述】:
根据 C++ 1998 标准第 3.5 节的第 3 条,const 引用具有内部链接。
具有命名空间范围 (3.3.5) 的名称如果是以下名称,则具有内部链接
显式声明为静态的对象、引用、函数或函数模板,或者,
显式声明为 const 且既未显式声明 extern 也未先前声明具有外部链接的对象或引用;或
匿名联合的数据成员。
但是为什么编译下面的代码会产生多重定义冲突呢?
// a.cpp
const int& a = 1;
int main()
{
return 0;
}
// b.cpp
const int& a = 1;
然后编译代码。
$ g++ a.cpp b.cpp
/tmp/ccb5Qi0M.o:(.bss+0x0): multiple definition of `a'
/tmp/ccD9vrzP.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status
如果将const引用改为const,如下
// a.cpp
const int a = 1;
int main()
{
return 0;
}
// b.cpp
const int a = 1;
编译就OK了。
【问题讨论】:
标签: c++ compiler-construction linker