Search code examples
cincludeglobal-variablesheader-filesc89

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


Solution

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