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?
views:
843answers:
4You can (should) declare it as extern
in a header file, and define it in exactly 1 .c file.
Note that that that c file should also use the header and that the standard pattern looks like:
// file.h
extern int x; // declaration
// file.c
#include "file.h"
int x; // definition and re-declaration, OK
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).
If you declare it like
int x;
in a header file which is then included in multiple places, you'll end up with multiple instances of x (and potentially compile or link problems).
The correct way to approach this is to have the header file say
extern int x; /* declared in foo.c */
and then in foo.c you can say
int x; /* exported in foo.h */
THen you can include your header file in as many places as you like.
The key is to keep the declarations of the variable in the header file and source file the same.
I use this trick
------sample.c------
#define sample_c
#include sample.h
(rest of sample .c)
------sample.h------
#ifdef sample_c
#define EXTERN
#else
#define EXTERN extern
#endif
EXTERN int x;
Sample.c is only compiled once and it defines the variables. Any file that includes sample.h is only given the "extern" of the variable; it does allocate space for that variable.
When you change the type of x, it will change for everybody. You won't need to remember to change it in the source file and the header file.