我有一个MyClass
声明公共枚举类型的 C++ 类,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"
}