Why does not包含定义的头文件const
并被多个源文件包含会产生编译错误multiple definition
?
const_in_header_file.h
const int num = 5;
//int x; //Error. Multiple defintion if included from multiple source files.
const_in_header_file_func.cpp
#include <iostream>
#include "const_in_header_file.h"
using namespace std;
void func(void)
{
cout << "num in func() = " << num << endl;
}
const_in_header_file_main.cpp
#include <iostream>
#include "const_in_header_file.h"
using namespace std;
extern void func(void);
int main()
{
cout << "num in main() = " << num << endl;
func();
}
在C++中,全局const是内部链接。将头文件与cpp文件合并后(头文件将被“插入”到#include所在的cpp文件中),每个编译单元将被编译为目标文件,然后链接在一起。这些函数和变量是内部链接,链接器看不到,这意味着您的 const global 在这个阶段不会被看到。即使不同的目标文件中有两个或多个常量,它们也只是隐藏的。
只有对于那些具有外部链接函数和变量的链接器才会尝试将声明与定义“组装”起来。
例如:
如果你有extern int a;
在一个编译单元中(插入 .h 的 C++);
链接器将搜索其定义:int a;
(没有外部关键字)。
如果找到两个,则会出现重新定义错误。
对于常量,它们只是对链接器隐藏。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)