0.c
int num;
//extern int num; <-- Are these two the same?
int main(){
return num;
}
1.c
int num; // same as `extern int num;` ?
2.c
int a = 1;
I like to ask 2 questions about the above snippets:
1- This linke says:
A tentative definition is an external declaration without an initializer, and either without a storage-class specifier or with the specifier static.
So based on this, is int num;
the same as extern int num;
in both 0.c
an 1.c
?
2- This compiles fine with gcc 0.c 1.c 2.c
. I have seen in other posts such as Why can I define a variable twice in C? which explain num
is a common symbol
. More specifically:
tentative definition becomes a full definition if the end of the translation unit is reached and no definition has appeared with an initializer for the identifier.
So according to this, both int num;
in 0.c
and 1.c
are considered full definitions
BUT they are not initialized.
This link says:
There may be more than one external definition for the identifier of an object, with or without the explicit use of the keyword extern; if the definitions disagree, or more than one is initialized, the behavior is undefined
So since we have 3 definitions, 2 of which are not initialized then this is considered defined behaviour and safe to use and num
will end up being 1
?