C/C++相互调用

来源:互联网 发布:手机淘宝店铺首页网址 编辑:程序博客网 时间:2024/06/01 23:17
C++调用C:
//xxx.c #include <stdio.h>        void hello()    {      printf("hello\n");    } 
编译:gcc -shared -fPIC -o libhello.so hello.c

cp libhello.so /lib/

调用:

// xxx.cpp    #include <iostream>        #ifdef __cplusplus    extern "C" {               // 告诉编译器下列代码要以C链接约定的模式进行链接    #endif    void hello();    #ifdef __cplusplus    }    #endifint main()    {      hello();      return 0;    } 
C调C++:
// xxx.cpp    #include <iostream>    void world()    {      std::cout << "world" << std::endl;    } 
编译: g++ -shared  -fPIC -o libworld.so world.cpp

cp libhello.so /lib/

做一个中间接口库,对C++库进行二次封装:


#include <iostream>        void world();        #ifdef __cplusplus    extern "C" {  // 即使这是一个C++程序,下列这个函数的实现也要以C约定的风格来搞!    #endif        void m_world()      {        world();      }     #ifdef __cplusplus    }    #endif  
编译:g++ -shared  -fPIC -o libmid.so mid.cpp -lworld

cp libmid.so /lib/


// xxx.c        #include <stdio.h>        int main()    {      m_world();          return 0;    } 
原创粉丝点击