Reputation: 5500
A.c
extern int x;
int x = -22;
int main(){}
B.c
void mai();
int x = 100;
void mai(){}
gcc A.c B.c -> gives multiple definition Error
A.c
extern int x;
int x = -22;
int main(){}
B.c
void mai();
int x;
void mai(){}
gcc A.c B.c -> Runs perfect.
Can someone explain me?
Upvotes: 0
Views: 318
Reputation: 385144
This is due to the "tentative definition" rule:
[C90: 6.9.2/2]:
A declaration of an identifier for an object that has file scope without an initializer, and without a storage-class specifier or with the storage-class specifierstatic
, constitutes a tentative definition. If a translation unit contains one or more tentative definitions for an identifier, and the translation unit contains no external definition for that identifier, then the behavior is exactly as if the translation unit contains a file scope declaration of that identifier, with the composite type as of the end of the translation unit, with an initializer equal to 0.
What this is saying is that your x
in B.c has file scope, so it does not conflict with the x
in A.c.
Note that this rule does not exist in C++; this is one example of C and C++ differing.
Upvotes: 2