• linux c++调用c


    参考 【Linux下gcc编译的四个过程】_Deacde_ZY的博客-CSDN博客

    C与C++如何互相调用_c文件引用c++头文件_卍一十二画卍的博客-CSDN博客

    Linux动态链接库的创建与使用_linux创建动态库_满天星羽的博客-CSDN博客

     c++调用c

    1.1 

    例子1: test1.c

    #include
    //#include "test1.h"
    void hello()
    {
       printf("hello world  11\n");

    }

    例子2:  直接在.cpp文件里面  使用extern "C"

    ///#include "test1.h"

    extern "C" 
    {
    extern  void hello();
    }

    int  main()
    {

    hello();

    }

    编译:g++ test1.c test2.cpp -o test88 报如下error

    原因: test1.c 并没有说明test1.c 里面的函数按照c的方式编译,而在test2.cpp里面是按照c的格式来使用。正确的方法应该分开编译,然后再链接:

    gcc -c test1.c  -o test1.o   // 1   参数-c 表示编译但不链接 这里只能用gcc 编译

    g++ -c test2.cpp -o test2.o  // 2  编译不链接

    g++ test2.cpp test1.o  test  //3   链接所有.o  

    注意:步骤2,3 可以综合成  g++ test2.cpp test1.o -o test 

    1.2 改进: 增加test1.h 文件,去除在test2.cpp 里面直接引用,改为使用test1.h头文件

    test1.h

    extern "C" 
    {
    extern void hello();
    }

    改进后的test2.cpp  使用头文件

    #include "test1.h"

    int  main()
    {

    hello();

    }

    编译:

    gcc -c test1.c  -o test1.o   // 1   参数-c 表示编译但不链接 这里只能用gcc 编译

    g++ test2.cpp test1.o -o test 

    改进3:test1.c 包含test1.h  g++编译test1.c时,在编译时先对test1.h 进行了预处理。仍然按照c的方式编译。

    test1.c

    #include
    #include "test1.h"
    void hello()
    {
       printf("hello world  11\n");

    }
    编译:一步到位

    g++ test1.c test2.cpp -o  test

    c++ 调用c的惯用方法: 在 .cpp文件中 加入 extern "C " { #include "test1.h"}

    test1.h
    extern void hello(); 
    当作为动态库给外部模块使用时 必须要加 extern
     

     test1.c

    #include
    void hello()
    {
       printf("hello world  11\n");

    }

    例子2:  直接在.cpp文件里面  使用extern "C"

    extern "C" 
    {
    #include "test1.h"
    }

    int  main()
    {

    hello();

    }

    编译:两步走

     gcc -c test1.c -o test1.o
     g++ test2.cpp  test1.o -o  test
     

    这种方法的优点是 不用对原来的c文件或c开源库做任何的改动. 推荐。

    1.3 编译动态库和使用

    -fPIC 或 -fpic 参数的作用是使得 gcc 生成的代码是与位置无关的,也就是使用相对位置。

    -shared参数的作用是告诉编译器生成一个动态链接库

    gcc test1.c -shared -fpic -o libtest1.so   // 生成动态库 -fpic 生成位置无关的代码

    g++ test2.cpp  -L . -ltest1  -o testcpp
     

  • 相关阅读:
    重刷单调栈
    在设计测试用例前你应该考虑的重点在哪里?
    聊聊logback的DynamicThresholdFilter
    基于LEX的词法分析实验
    统计语言模型笔记
    java操作office表格(POI与easyExcelg)
    EasyCode整合mybatis-plus的配置
    Parker驱动器维修COMPAX控制器维修CPX0200H
    Java面试题异常相关
    支持YUV和RGB格式两路视频同时播放
  • 原文地址:https://blog.csdn.net/weixin_29898767/article/details/133230914