我有一个名为abc.h的头文件,其中我想用外部链接定义一个常量.因此它包含声明
--------------- abc.h -------------------------
extern const int ONE = 1;
Run Code Online (Sandbox Code Playgroud)
接下来,我有main.cpp,我想使用ONE的值.因此我在使用它之前在main.cpp中声明了ONE
--------------- main.cpp中---------------------
extern const int ONE;
int main()
{
cout << ONE << endl;
}
Run Code Online (Sandbox Code Playgroud)
我收到错误"ONE的多个定义".
我的问题是,如何使用外部链接声明一个const,并在随后的不同文件中使用它,这样常量只有一个内存位置,而不是每个包含常量静态版本的文件.
我从main.cpp中删除了#include"abc.h",一切正常.
g ++ abc.h main.cpp -o main
ONE的地址在标题和主要内容中相同.所以它有效.
但我不明白编译器如何在main.cpp中解析ONE而不包含include语句的定义
似乎g ++做了一些魔术.这是一个不好的做法,main.cpp的读者不知道ONE声明在哪里,因为main.cpp中没有包含"abc.h"?
Bra*_*vic 10
abc.h:
extern const int ONE;
Run Code Online (Sandbox Code Playgroud)
abc.cpp:
#include "abc.h"
const int ONE = 1;
Run Code Online (Sandbox Code Playgroud)
main.cpp中:
#include "abc.h"
int main() {
cout << ONE << endl;
}
Run Code Online (Sandbox Code Playgroud)