1、引言
由于嵌入式开发中都是用C语言写的,但是很多开源代码都会C++的,因此为了能够方便快速的直接调用,最近就在研究如何能在C语言中调用C++代码。
2、具体步骤
这是在Ubuntu中的最终程序结果
需要的文件有box.cpp box.h main.c Makefile
其中box.cpp代码为:
#include "box.h"
#include<stdio.h>
// 混合编译就得把所有的东西都换掉,变成全部的纯C语言 但是可以用C++ 中的类操作。
//成员函数定义
double Box::getVolume(void)
{
return length * breadth * height;
}
void Box::setLength( double len )
{
length = len;
}
void Box::setBreadth( double bre )
{
breadth = bre;
}
void Box::setHeight( double hei )
{
height = hei;
}
//对外的程序接口
void output(void)
{
Box Box1;
double volume = 0.0;
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
volume = Box1.getVolume();
printf("Box1 的体积:%f \n", volume);
}
box.h的代码为
#ifndef __BOX_H__ //防止被重复包含
#define __BOX_H__
#ifdef __cplusplus
extern "C" {
#endif
class Box
{
public:
double length; // 长度
double breadth; // 宽度
double height; // 高度
// 成员函数声明
double getVolume(void);
void setLength( double len );
void setBreadth( double bre );
void setHeight( double hei );
};
void output(void);
#ifdef __cplusplus
}
#endif
#endif // __ANIMAL_H__
main.c 的代码为
#include<stdio.h>
int main(void)
{
output();
return 0;
}
Makefile的内容如下:
main:main.c box.o
gcc -lstdc++ main.c box.o -o main
box.o:box.cpp box.h
g++ -c box.cpp
.PHONY : clean
clean:
-rm box.o mains
然后再简单介绍下,研究了一下 其实主要就是有几个注意点,在.cpp中需要有一个给外部接口的函数,不能是类函数。然后这个函数可以调用c++中的类及类变量,但是不能在这个函数中加入C++的输入输出函数什么的,比如使用std::cout 会报错,
box.o:在函数‘output’中:
box.cpp:(.text+0x140):对‘std::cout’未定义的引用
box.cpp:(.text+0x145):对‘std::ostream::operator<<(double)’未定义的引用
box.cpp:(.text+0x14a):对‘std::basic_ostream<char, std::char_traits >& std::endl<char, std::char_traits >(std::basic_ostream<char, std::char_traits >&)’未定义的引用
box.cpp:(.text+0x152):对‘std::ostream::operator<<(std::ostream& (*)(std::ostream&))’未定义的引用
box.o:在函数‘__static_initialization_and_destruction_0(int, int)’中:
box.cpp:(.text+0x17b):对‘std::ios_base::Init::Init()’未定义的引用
box.cpp:(.text+0x18a):对‘std::ios_base::Init::~Init()’未定义的引用
collect2: error: ld returned 1 exit status
make: *** [main] 错误 1
我的看法是,C语言能调用C++的简单函数,因为这个简单函数符合C语言中的函数规范,当C++中与C语言的规范不一样时候,gcc编译器就读不懂了,就会报错。
以上是我的一点简单看法,如果有大佬解决了这个问题方便的话告知下。