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?
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.
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.
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.
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With