首页 > 解决方案 > 在c中使用重载的c++函数

问题描述

我之前用 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.
}

标签: c++cgccmakefileoverloading

解决方案


程序不编译是因为 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);
   }
}

推荐阅读