Header file containing 'const' included in multiple source files

徘徊边缘 提交于 2020-07-07 09:45:13

问题


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();
}

回答1:


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.




回答2:


Because if it really is a definition and not a declaration, then the compiler will create a (global) variable with the same name whenever it again and again encounters the definitoion - and then the linker doesn't know what to do with the multiple symbols with the same name in the resulting object code files.




回答3:


Probably because you wrote the header file ... but failed to include "header guards".

The lack of "header guards" would cause a compile error. Another possibility is that you failed to use "extern". This would cause a link error.

For example:

#ifndef MY_HEADER_H
#define MY_HEADER_H

extern int myglobal;

#endif

Please look at the above two links. Please post a snippet of the code that's failing if adding a guard and/or using "extern" don't resolve the problem.



来源:https://stackoverflow.com/questions/11980806/header-file-containing-const-included-in-multiple-source-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!