C与C++ 混合编译

来源:互联网 发布:成都软件测试工资 编辑:程序博客网 时间:2024/06/06 09:14

通常情况下,在用g++对源文件编译时,无论.c 还是.cpp 都是按照c++编译的,所以不会存在混合编译的问题

但是若用c++调用c编译器编译出来的库,就涉及到混合编译了

请看列子:

1.c

#include <stdio.h>#include "1.h"void out(int a,int b){printf("%d\n",a+b);}


gcc -c  1.c 生成1.o 

接下来在c++中调用

main.cpp

#include <iostream>#include "1.h"/*class point{public:void printout(){out(1,3);}};*/int main(){/*point st;st.printout();*/out(1,3);}
这个时候需要1.h头文件

#ifdef __cplusplusextern "C"{#endifvoid out(int a,int b); #ifdef __cplusplus}#endif
g++ main.cpp 1.o 编译成功

若去掉extern “C”

则提示:

root@ymzhi-desktop:/opt/vc# g++ main.cpp 1.o
/tmp/ccuNjqIj.o: In function `point::printout()':
main.cpp:(.text._ZN5point8printoutEv[point::printout()]+0x16): undefined reference to `out(int, int)'
collect2: ld returned 1 exit status


0 0
原创粉丝点击