understand “extern” in C

-apply to C variables and functions
-extends the visibility of the C variables and C functions

difference between declaration and definition
declaration  - exist somewhere in the program but the memory is not allocated 
                      (we could know the types from declarations)
definition - declaration + allocate memory for that variable/function
a variable/function can be declared any number of times but it can be defined one once
why? (cannot have two locations of the same variable/function)

extern

function

int foo(int arg1, char arg2); //extern exists by default
extern int foo(int arg1, char arg2);

The above two lines will be treated the same by C compiler since C compiler will add extern when compiling the first line.
Declaration can exist in several files and any files with the function declaration can use the function.
How C compiler works? By knowing the declaration of the function, C compiler knows that the definition of the function exists and it goes ahead to compile the program.
*extern implicit for C function


variable

extern int var;     //declaration only
int var;                //definition   
*extern explicitly for C variable

Conclusion

1.declaration can be done any number of times but definition only once
2.”extern” is used to extend the visibility of variables/functions
3.Since functions are visible through out the program by default, the use of extern is redundant.
4.When extern is used for a variable, it’s declared only
5.extern with initialization is allowed but with warning

One sentence: tell the program to find defintions in other files

//variable examples

#include<iostream>
using namespace std;
int var;
int main(){
	var =10;
	return 0;
}


// compile successfully <- defined and use (defined and not use is trivial)
// var is globally defined


extern int var;
int main(void)
{
  return 0;
}


//compile successfully <- declared only but not use
//var is globally declared


extern int var;
int main(void)
{
 var = 10;
 return 0;
}


//throw error <- declared only and use
//var is globally declared but not defined(no memory allocated for the variable)


#include "somefile.h"
extern int var;
int main(void)
{
 var = 10;
 return 0;
}


//compile successfully <- defined and use
//var is globally defined if somefile.h has the definition of var


extern int var = 0;
int main(void)
{
 var = 10;
 return 0;
}
// error <- declared with initialization
//from compiler: warning: 'extern' variable has an initializer [-Wextern-initializer]

Reference: https://www.geeksforgeeks.org/understanding-extern-keyword-in-c/

猜你喜欢

转载自blog.csdn.net/real_lisa/article/details/80811370