Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between using extern and #including header files?

Tags:

I am beginning to question the usefulness of "extern" keyword which is used to access variables/functions in other modules(in other files). Aren't we doing the same thing when we are using #include preprocessor to import a header file with variables/functions prototypes or function/variables definitions?

like image 405
Midnight Blue Avatar asked Aug 25 '09 18:08

Midnight Blue


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's the difference between extern and static?

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 .

What is the difference between extern in function and in function?

Explanation: extern int fun(); declaration in C is to indicate the existence of a global function and it is defined externally to the current module or in another file. int fun(); declaration in C is to indicate the existence of a function inside the current module or in the same file. Thanks for explaining the answer.

What is the point of extern?

the extern extends the visibility to the whole program, by externing a variable we can use the variables anywhere in the program provided we know the declaration of them and the variable is defined somewhere. Declarations of variables at file scope (Not in other files ) are external by default.


2 Answers

extern is needed because it declares that the symbol exists and is of a certain type, and does not allocate storage for it.

If you do:

int foo; 

In a header file that is shared between several source files, you will get a linker error because each source would have its own copy of foo created and the linker will be unable to resolve the symbol.

Instead, if you have:

extern int foo; 

In the header, it would declare a symbol that is defined elsewhere in each source file.

One (and only one) source file would contain

int foo; 

which creates a single instance of foo for the linker to resolve.

like image 200
Michael Avatar answered Sep 17 '22 05:09

Michael


No. The #include is a preprocessor command that says "put all of the text from this other file right here". So, all of the functions and variables in the included file are defined in the current file.

like image 25
jcopenha Avatar answered Sep 20 '22 05:09

jcopenha