HighPredator
HighPredator

Reputation: 772

Global variables in header files

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).

  1. Does this mean that in each *.c file exist two different variables with name i?

  2. What is the situation with declaration/definition in this example (in accordance with standard)?

Upvotes: 1

Views: 1708

Answers (4)

Adit Ya
Adit Ya

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

zafer-victory
zafer-victory

Reputation: 1

You will have linker error.

please search "extern" keyword.

Upvotes: 0

Vagish
Vagish

Reputation: 2547

You will get a linker error for multiple definition of variable.

Upvotes: 0

user694733
user694733

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

Related Questions