[http://stackoverflow.com/questions/1433204/how-do-i-use-extern-to-share-variables-between-source-files-in-c](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/](http://lpy999.blog.163.com/blog/static/117372061201182051413310/)
我們用extern將有多個源文件構建的程序中的源文件關聯在一起。相對一個程序來說,一個全局變量只能定義一次,但是可以用extern聲明多次。
**extern是去聲明和定義全局變量的最佳方式**
簡潔,可靠得聲明和定義一個全局變量是在頭文件去對變量用extern聲明。一個頭文件包含源文件定義的變量和被所有源文件引用的變量 的聲明。
對于任何一個程序來說,源文件定義變量,頭文件聲明對應變量。
~~~
//file1.h
extern 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.h
extern 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可省略,但是我強烈建議留下可以作為標識。噢這個是聲明。**
[關于變量定義和聲明的可以看這里](http://blog.csdn.net/jq_ak47/article/details/50541883)