Variable declaration in header file

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

+44
c header
Jul 22 '09 at 9:43
source share
5 answers

You must declare a variable in the 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, while the declaration simply enters the variable into the symbol table (and makes the linker look for it when it comes to link time).

+85
Jul 22 '09 at 9:50
source share

You can (should) declare it as extern in the header file and define it exactly in .c format.

Note that this .c file must also use a header and that the standard template looks like this:

 // file.h extern int x; // declaration // file.c #include "file.h" int x = 1; // definition and re-declaration 
+26
Jul 22 '09 at 9:47
source share

If you declare it as

 int x; 

in the header file, which is then included in several places, you will get multiple instances of x (and potentially compile or link problems).

The right way to approach this is to have a header file

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

+9
Jul 22 '09 at 9:51
source share

The key must contain variable declarations in the header file and the source file.

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 compiles only once and defines the variables. Any file that includes sample.h only gets the "extern" variable; it allocates space for this variable.

When you change type x, it will change for everyone. You will not need to change it in the source file and the header file.

+3
Jul 22 '09 at 13:37
source share

How about this solution?

 #ifndef VERSION_H #define VERSION_H static const char SVER[] = "14.2.1"; static const char AVER[] = "1.1.0.0"; #else extern static const char SVER[]; extern static const char AVER[]; #endif /*VERSION_H */ 

The only converse that I see is that the inclusion protector does not save you if you included it twice in the same file.

0
Aug 20 '14 at 21:51
source share



All Articles