Variable declaration in a header file

Ori Popowski picture Ori Popowski · Jul 22, 2009 · Viewed 102.1k times · Source

In case I have a variable that may be used in several sources - is it a good practice to declare it in a header? or is it better to declare it in a .c file and use extern in other files?

Answer

Martin B picture Martin B · Jul 22, 2009

You should declare the variable in a header file:

extern int x;

and then define it in one C file:

int x;

In C, the difference between a definition and a declaration is that the definition reserves space for the variable, whereas the declaration merely introduces the variable into the symbol table (and will cause the linker to go looking for it when it comes to link time).