Reputation: 7891
I have a simple .h file like this:
//test.h
int x = 12;
If I include this file in ,for example, main.cpp
and functions.cpp
linker will produce this error which is reasonable :
error LNK2005: "int x" (?x@@3HA) already defined in functions.obj
But when I change variable definition :
//test.h
const int x = 12;
The linker error goes away . Way?
Upvotes: 0
Views: 56
Reputation: 110658
A name declared at namespace scope that is const
has internal linkage. That is, each file you include test.h
into will have its own object named x
. See §7.1.1/7:
A name declared in a namespace scope without a storage-class-specifier has external linkage unless it has internal linkage because of a previous declaration and provided it is not declared
const
. Objects declaredconst
and not explicitly declaredextern
have internal linkage.
Upvotes: 5