Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable declaration in a header file [duplicate]

Tags:

c

header

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?

like image 320
Ori Popowski Avatar asked Jul 22 '09 09:07

Ori Popowski


People also ask

Can you declare variables in a header file?

Yes. Although this is not necessarily recommended, it can be easily accomplished with the correct set of macros and a header file. Typically, you should declare variables in C files and create extern definitions for them in header files.

What happens if a header file is included twice?

If a header file happens to be included twice, the compiler will process its contents twice. This is very likely to cause an error, e.g. when the compiler sees the same structure definition twice. Even if it does not, it will certainly waste time.

What will happen if the variable is declared in the .h file?

If you declare variables in a . H file, then that is the same as declaring them in your . C file, outside the functions, so as global variables.

What should I declare in header file?

You should declare it as extern in a header file, and define it in exactly 1 . c file. re-definition is an error but re-declaration is Ok and often necessary. 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.


1 Answers

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

like image 143
Martin B Avatar answered Sep 21 '22 17:09

Martin B