• Linux下C和C++相互调用


    目录

    C++调用C代码

    C代码调用C++代码

    C和C++几乎是不分仲伯,我们在写C代码或是C++代码时,常常会发生彼此混合调用的现象;而且C语言和C++语言都有一些独有的非常有价值的项目,因而两种语言的互操作,充分利用前人造的轮子是一件非常有价值的事情。

    C++调用C代码

    C++中相关的定义及声明

    #ifdef __cplusplus
    extern "C" {
    #endif // __cplusplus

    #include <stdio.h>
    void show();
    #ifdef __cplusplus
    }
    #endif

    int main(int argc, char *argv[])
    {
    show();
    return 0;
    }

    C代码中被调用函数的实现

    C头文件


    /*c头文件*/
    #ifndef __TEST_H__
    #define __TEST_H__

    void show();

    #endif
    C源文件


    /*c源文件文件*/
    #include "c_test.h"
    #include <stdio.h>

    void show()
    {
    printf("show in c is:%s\n", "Hello Word");
    }

    makefile文件

    cpp:
    gcc -c *.c
    g++ -c *.cpp
    g++ -o cpp_test *.o

    clean:
    rm *.o cpp_test

    编译及运行结果

    C代码调用C++代码

    C++中相关的定义及声明
    C++头文件


    #ifdef __cplusplus
    extern "C" {
    #endif

    void cpp_fun();

    #ifdef __cplusplus
    }
    #endif
    C++源文件


    #include "cpp_test.h"
    #include <stdio.h>

    #ifdef __cplusplus
    extern "C"
    {
    #endif

    void cpp_fun()
    {
    printf("cpp_fun :%s\n","Hello Word C");
    }

    #ifdef __cplusplus
    }
    #endif

    C代码中被调用函数的实现

    #include "cpp_test.h"

    int main()
    {
    cpp_fun();
    }

    makefille文件

    c:
    gcc -c *.c
    g++ -c *.cpp
    gcc -o c_test *.o -lstdc++
    clean:
    rm *.o c_test

    编译及运行结果


    ————————————————
    版权声明:本文为CSDN博主「XiaoCheng'Blog」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/qq_44045338/article/details/105746744

  • 相关阅读:
    POJ1201 Intervals
    POJ3169 Layout
    POJ1692 Crossed Matchings
    POJ1671 Rhyme Schemes
    POJ1742 Coins
    BZOJ2662: [BeiJing wc2012]冻结
    BZOJ 2330: [SCOI2011]糖果
    NOIP2015提高组T2 洛谷P2661 信息传递
    洛谷P1197 [JSOI2008]星球大战
    HDU3538 A sample Hamilton path
  • 原文地址:https://www.cnblogs.com/wanghuaijun/p/15966956.html
Copyright © 2020-2023  润新知