c++ - 在 C 中使用重载的 C++ 函数

标签 c++ c gcc makefile overloading

我之前用 C++ 代码编写了一个重载函数,现在我需要从 C 文件调用该函数。不幸的是,在我在 C 中包含 c++ 头文件后,Makefile 无法编译。 (我正在使用带有 c++11 标志的 g++)

这是我的问题:

  1. 程序编译不通过是因为C不支持函数重载吗?

  2. 如果 (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.
}

最佳答案

  1. Is the program not compiling because C does not support function overloading?

正确。

  1. 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/

相关文章:

c++ - 使用 ffmpeg.dll 或 avcodec.dll 将视频文件转换为 TIFF? "on-the-fly"可能吗?

c++ - 如何将事件悬停在标签上

c++ - 如何将结果存储到文本文件中?

c - 通过 pipe() 系统调用 : how to imitate pressing enter (during the input) in terminal? 向子进程传输数据

c++ - 无法从基类 C++ 访问变量

c - 读写整数数组到共享内存

c++ - 由于 `using` 导致命名空间不匹配导致 Doxygen 与 header 签名不同时无法解析 cpp 文件中的方法签名

我的代码的更正和提示

c++ - Fedora 22 - 编译 - __atomic_is_lock_free

c++ - std::stoi 实际上可以安全使用吗?