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
------
本文详细介绍了C/C++中extern关键字的使用方法,解释了如何声明外部变量和函数,并说明了其在头文件中的应用。通过具体代码示例展示了extern与static的区别,以及如何跨文件共享变量和函数。
2081

被折叠的 条评论
为什么被折叠?



