在Linux平台编译iLog3动态链接库时遇到的问题:`tls_g' can not be used when making a shared object
环境
在 Visual Studio 2015 上使用 Visual C++ for Linux 插件在远程 Linux 主机上编译和调试 C 程序。其中,日志库我打算采用 iLog3( Github上的 calvinwilliams/iLOG3 ),打算编译成动态链接库(Shared Library)供其它程序调用。
问题
建立 Cross Platform 的 Linux shared library 工程。此处并无特殊之处,按下不表。
但是在编译时,遇到了一些链接错误:
1>/usr/bin/ld : error : relocation R_X86_64_TPOFF32 against symbol `tls_g’ can not be used when making a shared object; recompile with -fPIC
1>/usr/bin/ld : error : relocation R_X86_64_TPOFF32 against symbol `_g_logc_pid’ can not be used when making a shared object; recompile with -fPIC
1>/usr/bin/ld : error : relocation R_X86_64_TPOFF32 against symbol `tls_gs’ can not be used when making a shared object; recompile with -fPIC
检索
通过搜索 gcc 的 -fPIC 编译选项,在 stackoverflow 上面看到了这个有价值的帖子:
GCC -fPIC option
https://stackoverflow.com/questions/5311515/gcc-fpic-option
阅读帖子发现 -fPIC 的含义就是 Generate position-independent code 的意思。
解决问题
在 Visual C++ 的 Code Generation 这一项目属性中,果然见到了 -fPIC 这个选项:
按照以上截图更改项目属性支持 -fPIC 编译选项之后,果然解决了这个编译链接的问题:
如以上截图所示,编译成功。