extern 关键字的作用

        **extern的作用**

demo.h 头文件

#ifndef _DEMO_H
#define _DEMO_H

#ifdef __cplusplus
extern "C"{         // point 1
#endif
    extern int a;   // point 2
    extern int b;
    extern int add(int, int);

#ifdef __cplusplus
}
#endif

#endif // !_DEMO_H

demo.c c源文件
全局变量、函数的定义

#include <stdio.h>

int a = 111;
int b = 20;

int add(int l, int r){
    printf("c program\n");
    return l + r;
}

其他源文件(c或者cpp)若想访问demo.c中的全局变量,只需包含demo.h即可。

分析:
1 . extern 关键字用来声明变量时,表明该变量的定义在其他源文件中,链接时去其他obj file中查找。
2. 为什么demo.h 中要区分 c++编译还是 c编译呢?因为c++源文件包含该头文件编译时, extern 声明的变量和函数都会按照c++的格式编译,但是链接时找不到这种格式的,因为定义是在demo.c文件中,定义编译格式也就是c格式类型,那么就必须区分开,所以使用 extern “C”来指定用c类型来编译。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值