C与C++ 混合编译

通常情况下,在用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 __cplusplus
extern "C"
{
#endif
void 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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值