extern 使用示例代码
时间: 2023-11-21 15:59:41 浏览: 25
extern 是 C/C++ 中的一个关键字,用于声明一个全局变量或函数,表示该变量或函数是在当前文件以外定义的。这样可以在当前文件中使用其他文件定义的全局变量或函数。
下面是一个使用 extern 声明全局变量的示例代码:
```c
// file1.c
#include <stdio.h>
int count; // 全局变量
void func() {
extern int count; // 使用 extern 声明全局变量
printf("count = %d\n", count);
}
int main() {
count = 5;
func();
return 0;
}
```
在上面的代码中,全局变量 count 被定义在文件 file1.c 中,然后在函数 func() 中使用 extern 声明,表示该变量是在当前文件以外定义的。在 main 函数中给 count 赋值为 5,然后调用 func 函数,输出 count 的值为 5。
下面是一个使用 extern 声明全局函数的示例代码:
```c
// file1.c
#include <stdio.h>
void func(); // 声明全局函数
int main() {
func();
return 0;
}
// file2.c
#include <stdio.h>
void func() { // 定义全局函数
printf("Hello, world!\n");
}
```
在上面的代码中,全局函数 func 被声明在文件 file1.c 中,然后在 main 函数中调用。在文件 file2.c 中定义了函数 func,具体实现输出一句话。因为在主函数中使用了 func 函数,在编译时需要链接 file2.c 文件中定义的 func 函数,使用 extern 声明可以将函数声明在 file1.c 文件中,让编译器知道该函数是在当前文件以外定义的。