|
An external variable has to be defined outside of any function; this allocates actual storage for it. The variable must also be declared in each function that wants to access it, this may be done either by an explicit extern declaration or implicitly by context. For Example:
#include <stdio.h> #define MAXLINE 1000
int getline(void); void copy(); char line[MAXLINE]; char save[MAXLINE]; int max;
int main(void) { int len; extern int max; extern char save[];
max = 0; while((len = getline()) > 0) { if(len > max){ max = len; copy(); } if(max > 0) printf("%s", save); return 0; }
int getline(void) { int c, i; extern char line[]; for(i = 0; i < MAXLINE - 1 && (c = getchar()) != EOF && c != '\n'; ++i) line[i] = c; if(c == '\n'){ line[i] = c; ++i; } line[i] = '\0'; return i; }
void copy(void) { int i; extern char line[], save[];
i = 0; while((save[i] = line[i] != '\0') ++i; }
注:在某些情况下,extern 声明可以省略:如果一个变量的extern定义发生在它被使用之前。 但是如果程序是在多个源文件中,如defined the variable in file1 and used in file2 then an extern declaration is needed in file2.
|