贡献者: addis
extern "C" {...} 的部分也是 C API。
__attribute__((attribute_name)) MSVC 和 MinGW 的 __declspec(attribute_name)。注意双层括号不可省略为单层。其中 attribute_name 在 __declspec 中可以是 dllimport 或 dllexport;若用 GCC/Clang 在非 Windows 系统跨平台使用则用 visibility("default") 表示 public,visibility("hidden") 表示 hidden(不区分 import/export)。
default/hidden 是对应了编译器选项 -fvisibility=default/hidden。
-fvisibility=default),而 MSVC 默认全部隐藏。只有导出的符号才可以被其他库或可执行文件使用。
-fvisibility=hidden)控制某个编译单元,或者用 linker 选项 -Wl,--exclude-all-symbols 隐藏当前编译的库的所有符号。
// mylib.h
// MYLIB_BUILDING 宏在编译 mylib.dll 时必须定义,在使用时必须没有定义
#if defined(_MSC_VER)
// MSVC handling
#ifdef MYLIB_BUILDING
#define MYLIB_API __declspec(dllexport)
#else
#define MYLIB_API __declspec(dllimport)
#endif
#elif defined(__GNUC__) || defined(__clang__)
// GCC/Clang - cross other platforms
#ifdef MYLIB_BUILDING
#define MYLIB_API __attribute__((visibility("default")))
#else
#define MYLIB_API
#endif
#else
#define MYLIB_API // Unknown compiler
#endif
class MYLIB_API MyClass { // Exported on all platforms
public:
void method();
};
MYLIB_API 只需要在声明符号的时候使用,不需要在定义时使用(除非定义和声明写在一起,例如 C++ template、inline 函数等)。
例如要在使用 MinGW 编译一个库给 MSVC 使用,除了使用 extern "C" {...},为了避免该库依赖 MinGW 特有的依赖库,应该把它们设置为静态链接。
# Compile with these flags to avoid MinGW dependencies
gcc -shared -o mylib.dll mylib.c \
-static \ # Static linking (crucial!)
-static-libgcc \ # Static libgcc
-static-libstdc++ \ # Static C++ runtime if needed
-Wl,--output-def,mylib.def \ # Generate .def file
-Wl,--out-implib,libmylib.a
 
 
 
 
 
 
 
 
 
 
 
友情链接: 超理论坛 | ©小时科技 保留一切权利