extern关键字理解

来源:互联网 发布:积分购物源码 编辑:程序博客网 时间:2024/06/06 05:53

http://stackoverflow.com/questions/1433204/how-do-i-use-extern-to-share-variables-between-source-files-in-c
http://lpy999.blog.163.com/blog/static/117372061201182051413310/

我们用extern将有多个源文件构建的程序中的源文件关联在一起。相对一个程序来说,一个全局变量只能定义一次,但是可以用extern声明多次。
extern是去声明和定义全局变量的最佳方式

简洁,可靠得声明和定义一个全局变量是在头文件去对变量用extern声明。一个头文件包含源文件定义的变量和被所有源文件引用的变量 的声明。
对于任何一个程序来说,源文件定义变量,头文件声明对应变量。

//file1.hextern int global_variable;/* Declaration of the variable 变量声明,必须用extern,不能省略*/
//file1.c#include "file1.h"/* Declaration made available here */#include "prog1.h"/* Function declarations 函数声明*//* Variable defined here */int global_variable =37;/* Definition checked against declaration 变量定义*/int increment(void){return global_variable++;}
//file2.c#include "file1.h"#include "prog1.h"#include <stdio.h> {    printf("Global variable: %d\n", global_variable++);}//That's the best way to use them.

//The next two files complete the source for prog1:

//prog1.hextern void use_it(void);extern int increment(void);
prog1.c#include"file1.h"#include"prog1.h"#include<stdio.h>{    use_it();    global_variable +=19;    use_it();    printf("Increment: %d\n", increment());return0;}

prog1 uses prog1.c, file1.c, file2.c, file1.h and prog1.h.

总结一句话,对于变量来说,声明必须用extern修饰变量;对于函数来说extern可省略,但是我强烈建议留下可以作为标识。噢这个是声明。

关于变量定义和声明的可以看这里

0 0