Windows下的DLL、Linux下的库或是C++中调用C的库,均可能用到import/export。本文讨论一种通用的import/export宏定义的使用实践。
如下所示,"common.h"定义了可以跨平台的import/export宏定义,"something.h"定义了某个类头文件的import/export定义,"something.cpp"实现类并export类,使用该类的文件仅需#include "something.h",由于没有定义宏SOME_EXPORTS,所以缺省是import啦。
"common.h"中包括:
#ifdef WIN32
#ifdef __cplusplus
#define DLL_EXPORT_C_DECL extern "C" __declspec(dllexport)
#define DLL_IMPORT_C_DECL extern "C" __declspec(dllimport)
#define DLL_EXPORT_DECL extern __declspec(dllexport)
#define DLL_IMPORT_DECL extern __declspec(dllimport)
#define DLL_EXPORT_CLASS_DECL __declspec(dllexport)
#define DLL_IMPORT_CLASS_DECL __declspec(dllimport)
#else
#define DLL_EXPORT_DECL __declspec(dllexport)
#define DLL_IMPORT_DECL __declspec(dllimport)
#endif
#else
#ifdef __cplusplus
#define DLL_EXPORT_C_DECL extern "C"
#define DLL_IMPORT_C_DECL extern "C"
#define DLL_EXPORT_DECL extern
#define DLL_IMPORT_DECL extern
#define DLL_EXPORT_CLASS_DECL
#define DLL_IMPORT_CLASS_DECL
#else
#define DLL_EXPORT_DECL extern
#define DLL_IMPORT_DECL extern
#endif
#endif
"something.h"中包括:
#include "common.h"
#ifdef SOME_EXPORTS
#define SOME_CLASS DLL_EXPORT_CLASS_DECL
#define SOME_API DLL_EXPORT_DECL
#else
#define SOME_CLASS DLL_IMPORT_CLASS_DECL
#define SOME_API DLL_IMPORT_DECL
#endif
class SOME_CLASS MyClass {}
SOME_API void MyFunc() {}
"something.cpp"实现MyClass,头文件包括:
#define SOME_EXPORTS
#include "something.h"
小鸡射手一直采用这种方法export DLL中的类,如Plugin的实现一文中谈到的C++实现Plugin。当然这也是借鉴OpenSource的做法的。