我之前用 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.
}
最佳答案
- Is the program not compiling because C does not support function overloading?
正确。
- If (1) is the case, what are some other options I can take to use the overloaded function?
如果你只需要调用其中一个函数,那么你可以为它写一个单独的头文件,这样你就可以在没有其他重载的情况下声明它。
如果您需要同时调用两者,那么您可以编写具有不同名称的包装函数,以提供与 C 兼容的 API。
关于c++ - 在 C 中使用重载的 C++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57154175/