I've heard that you shouldn't define anything in header files, because of the possibility of multiple defines, but if you have include guards, this shouldn't happen, right? What other reasons are there for adding extern to variables?
The extern must be applied in all files except the one where the variable is defined. In a const variable declaration, it specifies that the variable has external linkage. The extern must be applied to all declarations in all files. (Global const variables have internal linkage by default.)
Extern is a keyword in C programming language which is used to declare a global variable that is a variable without any memory assigned to it. It is used to declare variables and functions in header files. Extern can be used access variables across C files.
You do not necessarily "need" extern for variables. When C was invented Unix linkers were also written, and they advanced the art in unheralded but clever ways. One contribution was defining all symbols as small "common blocks".
static means a variable will be globally known only in this file. extern means a global variable defined in another file will also be known in this file, and is also used for accessing functions defined in other files. A local variable defined in a function can also be declared as static .
Include guards merely prevent multiple inclusion of a header within a single translation unit (aka compilation unit). This does not address the problem of multiple definitions from separate translation units at link time. Hence you should only ever put declarations in header (.h) files, and definitions in source (.c) files.
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