在头文件中声明变量的唯一逻辑方法是将它们声明为 extern
由于#include仅将头文件的文本插入源代码文件 ( https://godbolt.org/z/nor8nz ),您可以简单地在单个源文件中测试您的想法:
extern const int x;
int x;
Run Code Online (Sandbox Code Playgroud)
你会得到错误:
1
ARM gcc 8.2
- 347ms
<source>:4:5: error: conflicting type qualifiers for 'x'
int x;
^
<source>:2:18: note: previous declaration of 'x' was here
extern const int x;
^
Compiler returned: 1
Run Code Online (Sandbox Code Playgroud)