Reputation: 772
There is a header file foo.h
that contains a global variable declaration int i;
. This header file is being included in one.c
and two.c
respectively (I am aware that that's not a very good life choice, but it's not mine).
Does this mean that in each *.c file exist two different variables with name i
?
What is the situation with declaration/definition in this example (in accordance with standard)?
Upvotes: 1
Views: 1708
Reputation: 769
When you include the header file in another file, until they are compiled at a time i.e., they are in single translation unit, you wont get an error. But if you have to compile both the files i.e.,
gcc -c one.c two.c
Then yes, you are running into trouble.
It is nothing related to declaration/definition. Use static to have a file scope for the variable in question or change the design.
Upvotes: 1
Reputation: 16047
Yes, global variable i
with external linkage will exist in both compilation units. This will create conflict error during the linking phase.
In ideal situation, foo.h
header should contain declaration only: extern int i;
and the actual definition int i;
should exist only in one .c file.
Other alternative is to use static int i;
in foo.h
. This will create i
with internal linkage, meaning that variable is local on each compilation unit where header is included. However, declaring static
variables in headers is generally considered a bad practice.
Upvotes: 4