c++ - 在c中使用重载的c++函数
问题描述
我之前用 C++ 代码编写了一个重载函数,现在我需要从 C 文件中调用该函数。不幸的是,在我在 C 中包含 c++ 头文件后,Makefile 无法编译。(我正在使用带有 c++11 标志的 g++)
以下是我的问题:
程序不编译是因为 C 不支持函数重载吗?
如果 (1) 是这种情况,我可以采取哪些其他选择来使用重载函数?
cplusplus.h
#ifndef CPLUSPLUS_H
#define CPLUSPLUS_H
#ifdef __cplusplus
extern "C" {
"#endif"
void Foo(A a);
void Foo(B b);
#ifdef __cplusplus
}
"#endif"
cplusplus.cxx
#include "cplusplus.h"
extern "C" {
void Foo(A a) {
print(a.some_member);
}
void Foo(B b) {
print(b.some_member);
}
}
main.c
#include "cplusplus.h"
int main(int argc, char*argv[]) {
return 0; //Even without calling the function, an error throws.
}
解决方案
程序不编译是因为 C 不支持函数重载吗?
是的。
如果 (1) 是这种情况,我可以采取哪些其他选择?
C 接口必须使用未重载的函数名称,并且不使用任何其他不兼容的 C++ 工件。例如,您不能在extern "C"
函数中使用引用类型。
// C++ functions
void Foo(A a) {
print(a.some_member);
}
void Foo(B b) {
print(b.some_member);
}
// C-compatible layer.
extern "C" {
void Foo_A(A a) {
Foo(a);
}
void Foo_B(B b) {
Foo(b);
}
}
推荐阅读
- python - pyorient 查询引发“ struct.error: required argument is not an integer”
- amazon-s3 - 在 cloudflare 工作人员中使用 aws4fetch 包调用 AWS api?
- v8 - 预加载器 V8 无服务器
- python - 模糊正则表达式:替换的模糊计数始终为 1
- javascript - 如何在 React 中使用 map 函数显示对象数组中的图像链接?
- flutter - RenderFlex 子级具有非零弹性,但传入的高度约束是无界的
- python - 根据一行中的关键字将csv分成几部分,然后转置
- python - pyspark concat_ws 用于数组到字符串
- php - 如何让活动的 PHP 文件在 Microsoft Visual Code 中运行?
- docker - 如何在 ubuntu 容器中使用 docker