extern关键字理解

extern关键字在C语言中用于在多个源文件间共享变量。全局变量只能定义一次,但可以使用extern多次声明。推荐在头文件中用extern声明全局变量,源文件中定义。对于函数,extern可以省略,但建议保留以作标识。

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

http://stackoverflow.com/questions/1433204/how-do-i-use-extern-to-share-variables-between-source-files-in-c
http://lpy999.blog.163.com/blog/static/117372061201182051413310/

我们用extern将有多个源文件构建的程序中的源文件关联在一起。相对一个程序来说,一个全局变量只能定义一次,但是可以用extern声明多次。
extern是去声明和定义全局变量的最佳方式

简洁,可靠得声明和定义一个全局变量是在头文件去对变量用extern声明。一个头文件包含源文件定义的变量和被所有源文件引用的变量 的声明。
对于任何一个程序来说,源文件定义变量,头文件声明对应变量。

//file1.h

extern int global_variable;/* Declaration of the variable 变量声明,必须用extern,不能省略*/
//file1.c
#include "file1.h"/* Declaration made available here */
#include "prog1.h"/* Function declarations 函数声明*/
/* Variable defined here */
int global_variable =37;/* Definition checked against declaration 变量定义*/
int increment(void){return global_variable++;}
//file2.c
#include "file1.h"
#include "prog1.h"
#include <stdio.h> 
{
    printf("Global variable: %d\n", global_variable++);
}
//That's the best way to use them.

//The next two files complete the source for prog1:

//prog1.h

extern void use_it(void);
extern int increment(void);
prog1.c

#include"file1.h"
#include"prog1.h"
#include<stdio.h>
{
    use_it();
    global_variable +=19;
    use_it();
    printf("Increment: %d\n", increment());return0;
}

prog1 uses prog1.c, file1.c, file2.c, file1.h and prog1.h.

总结一句话,对于变量来说,声明必须用extern修饰变量;对于函数来说extern可省略,但是我强烈建议留下可以作为标识。噢这个是声明。

关于变量定义和声明的可以看这里

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值