extern修饰变量,表示其来自于其他文件
---------------------------------------
[root@localhost cpp]# cat source.c
#include<stdio.h>
static int height = 8848; // can only be used in this file
double pi = 3.14; //can be accessed from other file under the same project
int getHeight(){ // can be accessed from other file under the same project
return height;
}
--------------------------------------------
[root@localhost cpp]# cat main.c
#include<stdio.h>
int getHeight(); //or: external int getheight;
//extern double pi;
double getArea(double diameter){
extern double pi; // putting it here is also ok
return pi * diameter * diameter / 4;
}
int main(){
int height = getHeight();
printf("Height = %d\n", height);
double diameter = 2;
double area = getArea(diameter);
printf("diameter = %f, area = %f\n", diameter, area);
return 0;
}
-------------------------------------------
编译执行:
[root@localhost cpp]# gcc source.c main.c -o main
[root@localhost cpp]# ./main
Height = 8848
diameter = 2.000000, area = 3.140000
==========================================
2. extern的另外用法是当C和C++混合编程时,如果c++调用的是c源文件定义的函数或者变量,那么要加extern来告诉编译器用c方式命名函数:
文件A.cpp调用source.c里面的变量i和函数callme()
extern "C" //在c++文件里调用c文件中的变量
{
int j;
void callme();
}
int main()
{
callme();
}
二,static法则:
A、若全局变量仅在单个C文件中访问,则可以将这个变量修改为静态全局变量,以降低模块间的耦合度;
B、若全局变量仅由单个函数访问,则可以将这个变量改为该函数的静态局部变量,以降低模块间的耦合度;
C、设计和使用访问动态全局变量、静态全局变量、静态局部变量的函数时,需要考虑重入问题;