当前位置:首页>维修大全>综合>

c语言extern跟static可以一起用吗

c语言extern跟static可以一起用吗

更新时间:2023-05-03 11:38:31

c语言extern跟static可以一起用吗

//head file library.h

#ifndef LIBRARY_H

#define LIBRARY_h

extern FILE* logfile; //declaring an extern file pointer

/*other random codes*/

#endif

//end of head file

//source code main.c

#include

#include"library.h"

FILE* logfile; // declare the extern pointer is used in this file

int main()

{

logfile=fopen(...);

//main function

return 0;

}

//end of main.c

//source code backend.c

#include"libarary.h"

static FILE* logfile=fopen(...);

/*other random codes*/

//end of backend.c

如上所述,extern在头文件中声明一个跨文件的全局变量,每一个需要使用这个变量的文件都要单独声明(不加extern再声明一遍)

而static用于声明一个静态变量。静态变量不能被其他文件访问,因此可以与其他文件的全局变量同名。另外如果一个变量在文件中被声明为静态变量以后,该文件不能再有同名的跨文件全局变量

更多栏目