如何在Linux下编译含__declspec(dllexport)的代码且不修改源码
解决GCC编译Windows源码时__declspec(dllexport)的兼容问题
GCC 11.4不会自动将__declspec(dllexport)识别为__attribute__((dllexport)),你遇到的编译错误是因为编译器无法解析__declspec语法。以下是无需修改源码的非侵入式解决方法:
方法1:全局映射__declspec到GCC属性
在编译命令中添加预定义宏,将所有__declspec(x)替换为GCC兼容的__attribute__((x)):
g++ -D'__declspec(x)=__attribute__((x))' your_source.cpp -shared -o your_lib.so
这个宏会自动把代码中的__declspec(dllexport)转换为__attribute__((dllexport)),符合GCC的语法要求。
方法2:仅针对dllexport精准替换
如果只需要处理dllexport(无需兼容其他__declspec用法),可以用更针对性的宏定义:
g++ -D'__declspec(dllexport)=__attribute__((dllexport))' your_source.cpp -shared -o your_lib.so
额外说明
- 若源码中存在
__declspec(dllimport),Linux下可直接将其定义为空(因为动态库符号默认可见,无需显式导入):g++ -D'__declspec(dllexport)=__attribute__((dllexport))' -D'__declspec(dllimport)=' your_source.cpp -shared -o your_lib.so - 编译动态库时必须添加
-shared选项,生成Linux标准的.so文件。
内容的提问来源于stack exchange,提问作者Kyle McClellan
相关产品推荐
相关产品推荐

