extern 用法:

extern 用法:

    1.readme:extern 表明是“外部的” 与 static 相反,需要引用另一个文件中定义的 variable or function ,
        需要在调用之前 extern 声明它的存在。 一般都是在.h文件中声明。

    2.注意:
        在.h 文件中 variable 需要添加 extern,function 可以添加,也可以不添加 extern,.h文件中的function 默认是 extern 的。
        这是便于区分 声明 与 定义的 区别。 如果你一不小心在.h 定义了一个 variable ,每个文件都有 一个variable,这并非你的本意吧。
        static variable 应该定义在 source file中,不应该在 .h中。

    3.extern "C"
        这个是在 c++调用c时候出现,因为c++支持函数重载【利用名字粉碎机制】,所以c编译器与c++编译器生成的库文件以及.o文件
        函数名称形式不同,以至于连接出错。
    **example:**
        makefile:

        gcc -c c_fun.c -o c_fun.o
        g++ -c cpp_fun.cpp -o cpp_fun.o
        g++ cpp_fun.o c_fun.o

        file:cpp_fun.h
        #ifndef __CPP_FUN_H
        #define __CPP_FUN_H

        int get_a(void);

        #ifdef __cplusplus
        extern "C"{
        #endif
            void add(int a,int b);

        #ifdef __cplusplus  
        }
        #endif

        #endif

        file:c_fun.c
        #include <stdio.h>
        #include <string.h>
        #include <stdlib.h>

        void add(int a,int b)
        {
            printf("a+b=%d\n",a+b);
            return;
        }

        file:cpp_fun.cpp

        #include <iostream>
        #include <string>
        #include "cpp_fun.h"
        #include "cpp_fun.h"

        using namespace std;
        int a=7;
        int get_a(void)
        {
            return a;
        }

        int main(int argc,char *argv[])
        {
            add(get_a(),10);
            return 0;
        }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值