简体   繁体   中英

extern const in c++

I have a header file called abc.h in which i want to define a constant with an external linkage. Thus it contains the statement

---------------abc.h-------------------------

extern const int ONE = 1;

Next, i have main.cpp, where i want to use the value of ONE. Thus i declare the ONE in main.cpp before using it as

---------------main.cpp---------------------

extern const int ONE;
int main()
{
     cout << ONE << endl;
}

I get an error "Multiple definition of ONE".

My question is , how can i declare a const with external linkage, and use it subsequently in different files, such that there is ONLY one memory location for the constant as opposed to each file containing a static version of the constant.


I deleted the #include "abc.h" from main.cpp and everything works.

g++ abc.h main.cpp -o main

The address of ONE is same in header and the main. So it works.

But i dont understand how compiler resolves definition of ONE without include statement in the main.cpp

It seems like g++ does some magic. Is it a bad practice, where reader of main.cpp does not know where ONE is declared as there is no include "abc.h" in main.cpp ?

abc.h:

extern const int ONE;

abc.cpp:

#include "abc.h"

const int ONE = 1;

main.cpp:

#include "abc.h"

int main() {
     cout << ONE << endl;
}

The command line

g++ abc.h main.cpp -o main

causes the compiler to use header file abc.h as another module.

Usually one use #include "abc.h" and compiles with:

g++ main.cpp -o main


Line

extern const int ONE = 1;

is a definition , so it should be present in one module only. In headers we put declarations (without the assignments of actual value):

extern const int ONE;

They can be included into modules multiple times. When you include such declaration, your definition can omit "extern":

#include "abc.h"
const int ONE = 1;

(The question is 7 years old now, so the author know this already for sure, but I want to clarify it for others.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM