C调用C++的方法

来源:互联网 发布:网络计划六个时间参数 编辑:程序博客网 时间:2024/05/16 10:38
看了一下别人的文章,自己又整理了一下,贴上示例代码。
这是A.h
#ifdef __cplusplusextern "C"{#endifint printf_cpp();#ifdef __cplusplus}#endif
这是A.cpp
#include <iostream>using namespace std;extern "C"{int printf_cpp(void){        cout<<"c++ printf\n"<<endl;}}
然后编译生成.o文件
g++ -c a.cpp
在c中调用://main.c
#include "a.h"int main(int argc, char *argv[]){        printf_cpp();        return 0;}
编译时:gcc main.c A.o -o a.out -lstdc++
注意加上-lstdc++
这样就可以输出正确的结果了
也可以把它制作成库:ar rcs  liba.a a.o
然后编译:gcc main.c -I. -L. -la -lstdc++
也行

原创粉丝点击