Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extern variable - why?

Tags:

c

extern

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?

like image 259
someguy Avatar asked May 23 '11 21:05

someguy


People also ask

When should extern be used?

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

What is the use of extern in C?

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.

Is extern necessary in C?

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

Why do we use extern and static keywords?

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 .


1 Answers

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.

like image 122
Paul R Avatar answered Nov 15 '22 00:11

Paul R