extern基本使用

extern基本使用

作用:多个文件之间共享一个变量

方法一:

1
2
3
4
5
6
7
8
9
10
// fileA.c
int sharedVariable = 10; // 变量的定义与初始化

// fileB.c
extern int sharedVariable; // 变量的外部声明

void someFunction() {
// 现在可以访问 sharedVariable 变量了
sharedVariable = 20;
}

方法二:

使用头文件

需要注意的是,确保只在一个地方定义变量,否则会导致链接错误,因为链接器会遇到重复定义的问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// shared.h
#ifndef SHARED_H
#define SHARED_H
extern int sharedVariable;
#endif

// fileA.c
#include "shared.h"
int sharedVariable = 10;

// fileB.c
#include "shared.h"
void someFunction() {
sharedVariable = 20;
}

理解

第一种情况的理解:

在使用 extern 实现两个文件共享变量的时候,两个文件并不是“没有任何关联”。它们是通过 链接器(linker) 在编译后的链接阶段建立联系的

  • 一个 .c 文件中 定义 变量(分配存储空间);
  • 另一个 .c 文件中 声明 这个变量为 extern(告诉编译器:“这个变量存在别处,先别报错”);
  • 编译完成后,链接器会把这两个文件连接起来,找到那个变量的实际地址。

编译和链接命令(以 GCC 为例):

1
2
3
4
gcc -c fileA.c -o fileA.o
gcc -c fileB.c -o fileB.o
gcc -c main.c -o main.o
gcc fileA.o fileB.o main.o -o program

在多个文件中都定义了相同的全局变量:

1
2
3
4
5
// fileA.c
int sharedVar = 10;

// fileB.c
int sharedVar = 20; // 错误!链接时会报错:multiple definition of `sharedVar`

其他用法

声明外部函数

虽然函数默认就是具有外部链接性,但你可以显式地使用 extern 来声明一个在其他文件中定义的函数。

1
2
3
4
5
6
7
8
9
10
11
// fileA.c
void sayHello() {
printf("Hello!\n");
}

// fileB.c
extern void sayHello(); // 显式声明

void callSayHello() {
sayHello();
}

虽然不写 extern 也可以正常工作(因为函数默认就是外部的),但在头文件中使用 extern 可以增强可读性和一致性。

声明外部常量(如 const 全局变量)

在 C 中,const 变量默认是内部链接(static),所以如果你希望它被其他文件访问,必须加上 extern

1
2
3
4
5
6
7
8
9
// constants.c
extern const int MaxValue = 100;

// other.c
extern const int MaxValue;

void printMax() {
printf("%d\n", MaxValue);
}