s4eed
s4eed

Reputation: 7891

Why doesn't linker produce multiple definition error here?

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

Answers (1)

Joseph Mansfield
Joseph Mansfield

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 declared const and not explicitly declared extern have internal linkage.

Upvotes: 5

Related Questions