Variable declaration in a header file [duplicate]

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?


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


You should declare it as extern in a header file, and define it in exactly 1 .c file.

Note that the .c file should also use the header and so the standard pattern looks like:

// file.h
extern int x;  // declaration

// file.c
#include "file.h"
int x = 1;    // definition and re-declaration

re-definition is an error but re-declaration is Ok and often necessary.