应用于不同文件中的全局变量 && 关键字extern

 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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值