`

c extern

阅读更多

c extern

 

extern, used to declare variable / function, so that to use them before define them,

a external variable / function could only be define once, but could be declare multiple times,

extern, just declare the types, but will not allocate memory, memory is allocated only when define,

 

header file:

usually, put extern into a header file, so that to include by other source files,

 

static:

you should not use extern on static variable/function,


------
code:

ab.h:
// use extern to declare variable / function
extern int xa;
extern void fone();

a.c:
#include <stdio.h>
#include "ab.h"

// define variable xa
int xa = 10;

main() {
	// use function that declare by extern
	fone();
	printf("%d\n",xa);
}
 
b.c:
#include <stdio.h>
#include "ab.h"

// define function fone()
void fone() {
	// use variable that declare by extern
	xa = 11;
}
 

command to compile:
gcc a.c b.c

run:
./a.out

------

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics