Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extern const in c++

Tags:

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 ?

like image 642
Jimm Avatar asked Mar 12 '12 02:03

Jimm


Video Answer


2 Answers

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;
}
like image 67
Branko Dimitrijevic Avatar answered Oct 06 '22 01:10

Branko Dimitrijevic


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.)

like image 33
rha Avatar answered Oct 06 '22 00:10

rha