包含在多个源文件中的包含“ const”的头文件 [英] Header file containing 'const' included in multiple source files

查看:123
本文介绍了包含在多个源文件中的包含“ const”的头文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么包含 const 定义且包含在多个源文件中的头文件给出<$ c $的编译错误c>多个定义?

Why does not a header file containing the definition for a const and included by multiple source files give a compilation error for 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全局。即使在不同的对象文件中有两个或多个const,它们也只是被隐藏。
仅对于具有外部链接函数和变量的链接器,链接器将尝试汇编带有定义的声明。
例如:
如果您在一个编译单元(插入.h的cpp)中具有
extern int a;
链接程序将搜索其定义:
int a; (无外部关键字)。
如果找到两个,则会出现重新定义错误。

In C++ global const is internal linkage. After combining header file with cpp files (header file will be "inserted" into cpp files where #include is), each compilation unit will be compiled to object file and then be linked together. Those functions and variables are internal linkage will not be seen by linker, which means your const global will not be seen at this stage. Even if you have two or more const in different object files, they are just hidden. Only for those with external linkage functions and variables, linker will try to "assemble" the declaration with definition. For example: If you have extern int a; in one compilation unit (cpp with .h inserted); linker will search for it's definition: int a; (without external keyword). If it found two, redefinition error appears.

对于常量,它们只是隐藏在链接器中。

For constant, they are just hidden to linker.

这篇关于包含在多个源文件中的包含“ const”的头文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆