【发布时间】:2019-03-27 07:53:05
【问题描述】:
我有一个 C++ 类 MyClass,它声明了一个公共枚举类型 MyEnum,我想在 C 文件中使用该枚举。我该怎么做?
我试图在 C++ 文件中声明我的函数,然后将所有内容都作为 extern "C",但遗憾的是我正在使用 big_hugly_include.h 中定义的一些函数,并且这个头文件不喜欢被包含为 external "C"(它给了我template with C linkage 错误)。
我不能(不想)更改这个包含,我需要它,因为它定义了my_function_from_big_include。我卡住了吗?
my_class_definition.h:
class MyClass
{
public:
// I would like to keep it that way as it is mainly used in C++ files
typedef enum
{
MY_ENUM_0,
MY_ENUM_1,
MY_ENUM_2
} MyEnum;
};
尝试 1:my_c_function_definition.c:
#include "my_class_definition.h"
// I cannot remove this header
#include "big_hugly_include.h"
// foo is called in other C files
void foo()
{
// I need to call this function with the enum from the C++ class
// This doesn't work (class name scope does not exist in C)
my_function_from_big_include(MyClass::MyEnum::MY_ENUM_0);
}
尝试 2:my_c_function_definition.cpp:
#include "my_class_definition.h"
extern "C"
{
// Error template with C linkage
#include "big_hugly_include.h"
// foo is called in other C files
void foo()
{
// That would be ideal
my_function_from_big_include(MyClass::MyEnum::MY_ENUM_0);
}
// end of extern "C"
}
编辑以回应@artcorpse
尝试 3:my_c_function_definition.cpp:
#include "my_class_definition.h"
// Error multiple definition of [...]
// Error undefined reference to [...]
#include "big_hugly_include.h"
extern "C"
{
// foo is called in other C files
void foo()
{
// That would be ideal
my_function_from_big_include(MyClass::MyEnum::MY_ENUM_0);
}
// end of extern "C"
}
【问题讨论】:
-
如果你的枚举在一个类中,你不能从 C 中访问它。
-
除了将枚举移动/复制到全局命名空间之外,别无他法
-
为什么
typedef enum ...在 C++ 中? -
您的 .h 不是真正的 .h,因为至少缺少
class或struct和;。您还有其他遗漏的内容吗? -
为关闭此答案而提供的副本恕我直言不合适,因为它没有解决类型问题。
标签: c++ c types calling-convention cross-language