环境准备 - c和c++混合编程

说明

  • c++语言是c语言的升级版本,是基于C语言开发的,并且兼容C语言,在工作中很多时候需要C和C++混合开发,来充分利用两种语言的优势。
  • 混合开发时C++语言可以利用现有的c库,以节省开发时间;c语言也可以使用c++的新特性,来实现一些复杂的应用,例如:c++中有现成的一些容器(红黑树等),实际应用中经常需要使用到,没必要使用c再实现一套。

注意点

  1. c++为了实现函数重载,编译时对函数名进行了处理
例如:
char a(int b)
* 编译后函数名可能变成了 __ai;可以通过nm工具来查看导出的函数
  1. c++语言面向对象等新特性,c不支持

c++调用c

做法

  • 例子如下:
头文件:
#ifdef __cplusplus
extern "C" {
#endif

int cfun(int x);

#ifdef __cplusplus
}
#endif
  • C代码编译时编译器不会自带宏__cplusplus,而C++代码编译时编译器会自带该宏,来区分处理。
  • 不能去掉该条件编译,因为c编译器不支持extern “C”,会编译失败。
  • C++代码导入该头文件时,识别到extern “C”,就会按照C的方式去链接函数。

c调用c++

普通函数

做法

* 文件名: xxx.hpp
#ifdef __cplusplus
extern "C" {
#endif

int cppfun(int x);

#ifdef __cplusplus
}
#endif

* 文件名:xxx.cpp
#include <iostream>
#include <string>

#include "cppfun.hpp"

int cppfun(int x)
{
	std::string *a = new std::string("test");
	std::cout << "test in cppfun" << std::endl;
	return 1;
}

* 文件名:xxx.c
#include <stdio.h>
#include <stdlib.h>

#include "cppfun.hpp"

int main()
{
	cppfun(1);

	return 0;
}

* 编译
g++ -c cppfun.cpp
gcc -c cfun.c 
gcc cfun.o cppfun.o -lstdc++ -o test
  • 头文件中定义了按c方式导入函数,c++代码中一定要导入 该头文件,这样c++代码编译时才是按c的方式导出这些函数,链接时才能被找到。
  • 如果在c++代码中使用了c++的标准库,编译时需要链接stdc++库,这样链接时才能找到c++标准库实现。

做法

  • 给类加上一层包装,例如:
* c++ 类的包装头文件: warp_example.hpp
#ifdef __cplusplus
extern "C" {
#endif

void* create_example(int a);
int example_test(void *a);

#ifdef __cplusplus
}
#endif
* c++ 类的包装代码: warp_example.cpp
#include <iostream>
#include "cppfun.hpp" //c++ 类定义头文件
#include "warpcppfun.hpp" //c++ 包装头文件

void* create_example(int a)
{
	example *p = new example(a);
	return p;
}

int example_test(void *a)
{
	example *p = (example *)a;
	p->test();
	
	return 0;
}
* c 调用
#include <stdio.h>
#include "warpcppfun.hpp"

int main()
{
	void *p = create_example(10);
	
	example_test(p);
	
	return 0;
}

* 编译
g++ example.cpp -c
g++ warp_example.cpp -c 
gcc cmain.c -c
gcc cmain.o example.o warp_example.o -lstdc++ -o test
  • c++类在c中可以使用void*指针传递。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值