C/C++关键字:extern

一、extern:声明外部变量或外部函数

1.extern的作用

extern的作用:声明外部的全局变量或外部的函数,以实现跨文件使用其他.c/.h文件的全局变量或函数

编译时引用,链接时找定义


2.代码举例

①例1

以下两个.c文件:extern.c,main.c。我们使用extern关键字,在main.c中声明并调用extern.c中的全局变量和函数

//extern.c
int global = 10;

void bar() {
	static cnt = 0;
	cnt++;
	printf("cnt = %d\n", cnt);
}
//main.c
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

//声明外部全局变量
extern global;
//声明外部函数
extern bar();

int main(void) {
	//extern关键字
	printf("extern global = %d\n", global);
	int m = 5;
	while (m--) {
		bar();
	}

	return 0;
}

②例2

加入static关键字

//extern.c
int global = 10;

void bar() {
	static cnt = 0;
	cnt++;
	printf("cnt = %d\n", cnt);
}
//main.c
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

//static关键字
//extern关键字:extern + 全局变量/函数,则可使用其他文件声明的全局变量/函数

void fun() {
	static count = 0;
	count++;
	printf("count = %d\n", count);
}

//声明外部全局变量
extern global;
//声明外部函数
extern bar();

int main(void) {
	//static关键字
	int n = 3;
	while (n--) {
		fun();
	}
	printf("\n");

	//extern关键字
	printf("extern global = %d\n", global);
	int m = 5;
	while (m--) {
		bar();
	}

	return 0;
}

输出结果:
在这里插入图片描述


③例3

加上.h头文件,.c文件中包含对应的头文件

//extern.h
int globalVar = 20;
//extern.c
#include "extern.h"
int global = 10;

void bar() {
	static cnt = 0;
	cnt++;
	printf("cnt = %d\n", cnt);
}
//main.c
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

//static关键字
//extern关键字:extern + 全局变量/函数,则可使用其他文件声明的全局变量/函数

void fun() {
	static count = 0;
	count++;
	printf("count = %d\n", count);
}

//声明外部全局变量
extern global;
extern globalVar;
//声明外部函数
extern bar();

int main(void) {
	//static关键字
	int n = 3;
	while (n--) {
		fun();
	}
	printf("\n");

	//extern关键字
	printf("extern global = %d\n", global);
	printf("extern globalVar = %d\n", globalVar);
	int m = 5;
	while (m--) {
		bar();
	}

	return 0;
}

输出结果:
在这里插入图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员爱德华

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值