If I don't odr-use a variable, can I have multiple definitions of it across translation units?
Posted
by
sftrabbit
on Stack Overflow
See other posts from Stack Overflow
or by sftrabbit
Published on 2012-10-19T16:44:03Z
Indexed on
2012/10/19
17:01 UTC
Read the original article
Hit count: 156
The standard seems to imply that there is no restriction on the number of definitions of a variable if it is not odr-used (§3.2/3):
Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program; no diagnostic required.
It does say that any variable can't be defined multiple times within a translation unit (§3.2/1):
No translation unit shall contain more than one definition of any variable, function, class type, enumeration type, or template.
But I can't find a restriction for non-odr-used variables across the entire program. So why can't I compile something like the following:
// other.cpp
int x;
// main.cpp
int x;
int main() {}
Compiling and linking these files with g++ 4.6.3, I get a linker error for multiple definition of 'x'
. To be honest, I expect this, but since x
is not odr-used anywhere (as far as I can tell), I can't see how the standard restricts this. Or is it undefined behaviour?
© Stack Overflow or respective owner