在C语言中,extern关键字用于声明一个变量或函数,表示它在其他源文件中定义
以下是extern关键字在C语言多文件编程中的应用示例:
假设有两个源文件:main.c和file1.c。在file1.c中定义一个全局变量count,然后在main.c中使用extern关键字声明它。
file1.c:
#include<stdio.h>int count = 0;void increment() { count++;}main.c:
#include<stdio.h>// 使用extern关键字声明count变量extern int count;// 使用extern关键字声明increment函数extern void increment();int main() { printf("Before increment: %d\n", count); increment(); printf("After increment: %d\n", count); return 0;}声明全局函数假设有两个源文件:main.c和file2.c。在file2.c中定义一个全局函数add,然后在main.c中使用extern关键字声明它。
file2.c:
#include<stdio.h>int add(int a, int b) { return a + b;}main.c:
#include<stdio.h>// 使用extern关键字声明add函数extern int add(int a, int b);int main() { int result = add(3, 4); printf("Result: %d\n", result); return 0;}总之,extern关键字在C语言多文件编程中非常有用,它可以让你在不同的源文件之间共享变量和函数。只需确保在使用extern声明时,变量或函数已经在其他源文件中定义。


