共计 1769 个字符,预计需要花费 5 分钟才能阅读完成。
✨有的时候,当我想在 c 代码中调用 c ++ 接口,而后就编译报错了!!!
引出问题
C++ 反对函数重载的, 函数名雷同然而参数不同的重载函数在编译后链接的名字并不相同而能够被辨认, 这种状况下, 咱们引入一个中间层的办法同样能够实现 C 中调用 C ++ 的函数接口。
其实这与 C 中调用 C ++ 非重载根本函数成员的实现没有什么区别, 只是为各个重载函数均实现一套接口而已。
通常的做法
//test.cpp
#include <iostream>
#include "hello.h"
int getNum() {
std::cout << "get number" << std::endl;
return 123456;
}
这时,咱们须要对该 c++
函数,进行申明,通知编译器,须要按 c 的命名规定来:
//test.h
#ifdef __cplusplus
extern "C" {
#endif
int getNum();
#ifdef __cplusplus
}
#endif
#endif
这时,咱们就能够在 C
源码中调用 getNum
接口了。
重载函数
如果你想在 C
里调用重载函数,则必须提供不同名字的包装,这样能力被 C
代码调用。首先是咱们的 C++
接口, 如下所示:
// add.cpp
//#include <iostream>
int add(const int a, const int b)
{return (a + b);
}
double add(const double a, const double b)
{
//std::cout <<a <<"," <<b <<std::endl;
return (a + b);
}
咱们为此实现一个中间层 libadd.cpp
, 通过C++
编译器用 extern "C"
将其编译成 C 编译器可辨认的接口:
// libadd.cpp
int add(const int a, const int b);
double add(const double a, const double b);
#ifdef __cplusplus
extern "C"
{
#endif
int call_cpp_add_int(const int a, const int b)
{return add(a, b);
}
double call_cpp_add_double(const double a, const double b)
{return add(a, b);
}
#ifdef __cplusplus
}
#endif
最初是咱们的 C 源程序, 调用咱们的中间层:
// main.c
#include <stdio.h>
#include <stdlib.h>
int call_cpp_add_int(const int a, const int b);
double call_cpp_add_double(const double a, const double b);
int main( )
{printf("2 + 4 = %d\n", call_cpp_add_int(2, 4));
printf("2.1 + 4.5 = %lf\n", call_cpp_add_double(2.1, 4.5));
return 0;
}
唔,完满!
当然也能够把函数申明括起来~
// libadd.cpp
int add(const int a, const int b);
double add(const double a, const double b);
#ifdef __cplusplus
extern "C"
{
#endif
int call_cpp_add_int(const int a, const int b);
double call_cpp_add_double(const double a, const double b);
#ifdef __cplusplus
}
#endif
int call_cpp_add_int(const int a, const int b)
{return add(a, b);
}
double call_cpp_add_double(const double a, const double b)
{return add(a, b);
}
关注 && 分割
gitee:https://gitee.com/cmcc-oneos/OneOS-Lite
docs:https://oneos-lite.com/
援用自:https://gitee.com/cmcc-oneos/OneOS-Lite/blob/dev/docs/quick_guide/cplusplus/c-call-c++.md