c语言extern关键字的理解和使用
1 extern的作用
在c语言中,全局变量或者函数在整个工程是可见的,需要通过extern进行引用。extern用在函数或全局变量的声明前,表明此变量或此函数是在其他源文件中定义的,要在此文件中引用。
除了extern,还可以直接包含要引用变量函数所在头文件来实现,相比来说,extern的引用方式更加简洁,想引用哪个变量或函数直接在本文件中直接用extern声明即可,能加速编译时预处理过程,节省时间。
2 extern的理解
- extern用于声明外部函数或变量,作用域是从extern声明处到源文件结尾。
- extern int A= 10;和int A = 10;是等价的,都是定义,extern int A;表示声明。
- extern声明函数和变量时的不同点:函数声明前的extern可以省略,因为声明全局函数默认前面带有extern,建议统一都加上extern。
- 如果一个源文件中定义的函数或变量不想让其他文件引用,static可以实现数据隐藏,类似C++中的private属性,static函数只在定义它的源文件中可见。
- include某个头文件时,实际是原封不动的把头文件中的内容搬到#include位置,如果一个头文件中定义了一个变量,有两个原文件同时引用了该头文件,则会报multiple defined编译错误。因为一个变量或函数只能定义一次,可以声明多次。所以尽量不要在头文件中定义变量。
3 extern的用法示例
3.1 头文件形式引用
在File1.c中定义一个函数和全局变量,在File1.h中通过extern进行声明,在File2.c中引用头文件File1.h。
File1.c:
#include "File1.h"
#include "stdafx.h"
int FileNumber = 100;
void FileOutput()
{
printf("File1 Output!\n");
}
File1.h:
#include "stdafx.h"
#include <stdlib.h>
/* 头文件中进行声明 */
extern void FileOutput();
extern int FileNumber;
File2.h:
#include "stdafx.h"
#include <stdlib.h>
#include "File1.h"
int main(int argc, _TCHAR* argv[])
{
FileOutput();
printf("FileNumber: %d\n", FileNumber);
system("pause");
return 0;
}
Output:
File1 Output!
FileNumber: 100
3.2 extern直接引用
在File1.c中定义了一个函数和全局变量,File2.c中用extern声明变量,函数的声明没有用extern,依然可以调用。
File1.c
#include "File1.h"
#include "stdafx.h"
int FileNumber = 100;
void FileOutput()
{
printf("File1 Output!\n");
}
File1.h:
#include "stdafx.h"
#include <stdlib.h>
File2.c
#include "stdafx.h"
#include <stdlib.h>
/* 此处对函数的声明省略了extern */
void FileOutput();
extern int FileNumber;
int _tmain(int argc, _TCHAR* argv[])
{
FileOutput();
printf("FileNumber: %d\n", FileNumber);
system("pause");
return 0;
}
Output:
File1 Output!
FileNumber: 100
3.3 static使用
在File1.c定义的全局变量前加static,File2.c中extern声明,编译时报错。
File1.c
#include "File1.h"
#include "stdafx.h"
/* 用static定义全局变量 */
static int FileNumber = 100;
void FileOutput()
{
printf("File1 Output!\n");
}
File1.h:
#include "stdafx.h"
#include <stdlib.h>
File2.c
#include "stdafx.h"
#include <stdlib.h>
void FileOutput();
extern int FileNumber;/* 声明别处定义的static变量会报错 */
int _tmain(int argc, _TCHAR* argv[])
{
FileOutput();
printf("FileNumber: %d\n", FileNumber);
system("pause");
return 0;
}
Error:
error LNK2001: unresolved external symbol "int FileNumber" (?FileNumber@@3HA)
extern在C语言中用于声明外部变量或函数,允许在不同源文件间共享。它可以避免在头文件中定义导致的重复定义问题。静态变量static则提供数据隐藏,限制其在定义它的源文件内可见。文章通过示例展示了extern的三种用法:头文件引用、直接引用和与static的对比。
1366

被折叠的 条评论
为什么被折叠?



