1

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

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
HighPredator
  • 790
  • 4
  • 21

4 Answers4

4

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.

user694733
  • 15,208
  • 2
  • 42
  • 68
  • Ok, so technically we have 2 `int i;`-s in each *.c file, right? What about the tentative definition aspect? As far as I understand, `int i;` will be considered a definition only if there is no other definition of it. Is this why an error will occur, or is it smth else? – HighPredator Jun 09 '14 at 10:47
  • 1
    Yes one `i` on each file, total of 2. You are describing situation where `int i` is defined twice in the same compilation unit. You may write `int i;int i;`, and it will only produce 1 `i`. This is not the case here. This conflict happens later in the linking phase, when there are 2 `i`s from different compilation units. – user694733 Jun 09 '14 at 10:56
  • Thanks. Now I get it. Was not totally sure because the program that was performing linking (not a common linker) threw no errors. – HighPredator Jun 09 '14 at 10:59
  • Any kind of non-constant variable placed in a header file is considered very bad practice. – Lundin Jun 09 '14 at 11:04
1

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.

Adit Ya
  • 731
  • 1
  • 8
  • 19
0

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

Vagish
  • 2,520
  • 19
  • 32
0

You will have linker error.

please search "extern" keyword.