tags:

views:

843

answers:

4

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?

+7  A: 

You 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
Henk Holterman
Indeed it *should* always use the header, so that if the types get out of whack between the declaration and definition the compiler will tell you.
caf
cat, you're right, I'll re-word it a little.
Henk Holterman
+11  A: 

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

Martin B
+2  A: 

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.

Vicky
+2  A: 

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.

Robert
How do you deal with initialisation? - extern int x = 6; would give a warning on most compilers.
Dipstick
@chrisharris - that is a limitation. I usually have an Init() in each module to initialize variables.
Robert