几行代码值一千字:
我有三个简单的文件:header.h、main.cpp、other.cpp
==== CODE BEGIN ====
// header.h
#pragma once
const void* p = 0;
// main.cpp
#include "header.h"
int main()
{
return 0;
}
// other.cpp
#include "header.h"
==== CODE END ====
在编译最简单的项目时,VC++ 2010 报错如下:
ClCompile:
other.cpp
main.cpp
Generating Code...
other.obj : error LNK2005: "void const * const p" (?p@@3PBXB) 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 的错误,因为以下两个参考:
C++ 标准说:(在 n3126 的第 140 页)
“声明为 const 且未显式声明为 extern 的对象具有内部链接。”
MSDN说:
“在 C 中,常量值默认为外部链接,因此它们只能出现在源文件中。在 C++ 中,常量值默认为内部链接,这允许它们出现在头文件中。
const 关键字也可以用在指针声明中。”