几行代码值一千字:
我有三个简单的文件:header.h、main.cpp、other.cpp
// header.h
#pragma once
inline const int& GetConst()
{
static int n = 0;
return n;
}
const int& r = GetConst();
// main.cpp
#include "header.h"
int main()
{
return 0;
}
// other.cpp
#include "header.h"
在编译最简单的项目时,VC++ 2010 报错如下:
ClCompile:
other.cpp
main.cpp
Generating Code...
other.obj : error LNK2005: "int const & const r" (?r@@3ABHB) already defined in main.obj
D:\Test\Debug\bug.exe : fatal error LNK1169: one or more multiply defined symbols found
Build FAILED.
Time Elapsed 00:00:00.29
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
我确信这是 VC++ 2010 的错误,因为以下两个参考:
1,C++ 标准说:(在 n3126 的第 140 页)
“声明为 const 且未显式声明为 extern 的对象具有内部链接。”
2,MSDN 说:(在:http: //msdn.microsoft.com/en-us/library/357syhfh (VS.80).aspx )
“在 C 中,常量值默认为外部链接,因此它们只能出现在源文件中。在 C++ 中,常量值默认为内部链接,这允许它们出现在头文件中。
const 关键字也可以用在指针声明中。”