extern 是在C/C++中用来声明全局变量的。有时,一个变量或者函数,如果在多个文件中被调用,那么每一个文件的编译过程中都会生成自己的变量。举例来说,
//Tree.h
#ifndef tree_h
#define tree_h
#include <stdbool.h>
#include <stdlib.h>
typedef struct tree_node* node_ptr;
struct tree_node {
char* word;
node_ptr leftNode, rightNode;
};
node_ptr start = NULL;
void addItem(char*, int);
void display();
#endif
//tree.c
#include "tree.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void addItem(char arr[], int mode) {
node_ptr temp, temp2;
temp = (node_ptr)malloc(sizeof(struct tree_node));
temp->leftNode=NULL;
temp->rightNode=NULL;
if(mode == 1){
temp->word = arr;
start = temp;
}
}
void display() {
node_ptr temp;
temp = start;
printf("%s", start->word);
}
//main.c
#include "tree.h"
#include <stdio.h>
#include <conio.h>
int main() {
char word[31];
printf("Enter Root Word: ");
gets(word);
addItem(word, 1);
}
编译中程序会报错,因为main.c 和 tree.c 都include了tree.h,所以在编译的时候,都会产生自己关于变量start的定义,这样也就产生了重复定义。正确的做法是在header 的start前面加入关键字extern. 这样其他的文件include header的时候就不会去尝试生成自己的start,并且在tree.c中声明变量node_ptr start