请在这里帮助我,因为我一半相信我不能做我想做的事,一半相信应该有一个适当的解决方法。
我有一个用C++实现的DLL,因此将某些类导出到链接到它的其他C++模块。没关系。现在,我想从C模块(另一个DLL)链接到该DLL,因此我将提供一个“扁平化”的C接口(interface)并在内部处理C++内容。也可以
问题是我想将其作为单个.h和关联的.lib提供给C或C++客户端。因此,我的DLL中具有类似于以下内容的内容:
#ifdef DLL_EXPORTS
#define DLL_API __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)
#endif
// export a class for the C++ clients
class DLL_API CExportedClass
{
public:
CExportedClass();
// etc. etc.
};
// export flattened C interface for non-C++ clients
#ifdef __cplusplus
extern "C" {
#endif
DLL_API void DoSomethingInternally(); // i.e. implementation uses CExportedClass
#ifdef __cplusplus
}
#endif
当然,这在导入到C++模块中时效果很好,但是在导入到C模块中时由于无法识别
class
声明而无法编译。那么我以为我可以做到这一点我是否错了?我需要拆分为两个标题吗?在
#ifdef __cplusplus
声明(或其他某种class
)周围使用#ifdef
是否正确并且可以接受?真正在这里争取一个“干净”的答案。
最佳答案
MSDN上有几篇关于混合C和C++的文章:
我认为您可以简单地查看windows.h或类似的 header ,它们对于C和C++都可以正常工作,没有任何问题。
基本上是这样的:
头文件的开头
#ifndef _MYHEADER__H
#define _MYHEADER__H
#ifdef __cplusplus
extern "C" {
#endif
//Decalrations
//........
//........
//Bottom of your header
#ifdef __cplusplus
}
#endif
#endif
因此您的 header 应如下所示:
#ifdef DLL_EXPORTS
#define DLL_API __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)
#endif
#ifdef __cplusplus
//This part of header is not visible for ANSI C compiler
// export a class for the C++ clients
class DLL_API CExportedClass
{
public:
CExportedClass();
// etc. etc.
};
#endif
#ifdef __cplusplus
extern "C" {
#endif
DLL_API void DoSomethingInternally(); // i.e. implementation uses CExportedClass
#ifdef __cplusplus
}
#endif
这就是ANSI C编译器的外观:
#ifdef DLL_EXPORTS
#define DLL_API __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)
#endif
DLL_API void DoSomethingInternally();
这是C++编译器的外观:
#ifdef DLL_EXPORTS
#define DLL_API __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)
#endif
class DLL_API CExportedClass
{
public:
CExportedClass();
// etc. etc.
};
extern "C" {
DLL_API void DoSomethingInternally();
}
但是,您在 header 中声明类,因此C编译器对此不满意,应将其放在“C”声明之外。
在这里看看:
http://www.parashift.com/c++-faq/mixing-c-and-cpp.html