c extern

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

------

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值