[C语言

A. extern函数


一个c文件生成一个obj文件
 
外部函数:允许其他文件访问、调用的函数(默认函数为外部函数),不允许存在同名的外部函数
 
my.c
1 //define a extern function perfectly
2 void extern testEx()
3 {
4     printf("my.c ==> call external function
");
5 }
6  
main.c
1 //declare the function first to apply the C99 compiler standard
2 void extern testEx();
3 
4 int main(int argc, const char * argv[]) {
5     testEx();
6     return 0;
7 }
 
B. static函数
内部函数:只能在当前文件中使用的函数,不同的源文件可以有同名的内部函数
使用static修饰就可以定义内部函数
 
one.c
1 static void one()
2 {
3     printf("one.c ==> one()
");
4 }
5  
 
C.extern 与全局变量
java中可以调用后定义变量
c不能使用定义前的全局变量
ps:定义和声明是两个不同的步骤
 1 //first solution, define the variable before calling
 2 //int a;
 3 
 4 //declare a variable
 5 extern int a;
 6 
 7 int main(int argc, const char * argv[]) {
 8    
 9     a = 10;
10    
11     return 0;
12 }
13 
14 //define the variable
15 int a;

若想在某个全局变量声明之前使用,就需要使用extern修饰变量,表示该变量即将在下面定义。
1 void test()
2 {
3     extern int b;
4     printf("b = %d
", b);
5 }
6 
7 int b = 3;
 
D.static和全局变量
定义和声明一个内部变量,只能被本文件访问,不能被其他文件访问
 
 
E.static与局部变量
被static修饰的局部变量,生命周期能周延长到程序结束
但是作用域没有改变
1 void test()
2 {
3     static int e = 10;
4     e++;
5     printf("e = %d
", e);
6 }
main调用
    test();
    test();
    test();
 
out:
e = 11
e = 12
e = 13
 
 
F.全局/局部变量:
变量可以在函数内部或者外部声明
 
a.全局变量中:
全局变量(函数外)可以重复声明,不能重复定义
int a;//标记为weak,允许进行定义
int a = 4;//succuss,标记为strong,以此变量为同名全局变量的标准,不允许进行多重定义
int a = 5;//error
如在不同的源文件中存在同名全局变量,都是指的同一个变量
 
b.局部变量:
局部变量(函数内)不能重复声明
 
内部变量对外部变量的影响
可以区分开两个同名变量
 
 
static & extern 总结
extern能够声明一个全局变量,但是不能定义?
—》能声明,不能重复定义
static 可以声明并定义一个内部变量?
 
 
 
     
原文地址:https://www.cnblogs.com/hellovoidworld/p/4087106.html