【PE/compiler】Mac平台编译加-static选项链接静态库报错

Date: 2018.9.26


1、问题记录

Mac平台编译demo加-static选项链接静态库报如下错误:

ld: library not found for -lcrt0.o
clang: error: linker command failed with exit code 1
2、原因分析

gcc -v or clang -v

Apple LLVM version 6.1.0
Target:x86_64 -apple-arwin14.3.0
Thread model: poxsix

原因:clang编译器不支持静态编译参数-static。
This won’t work. From the man page for gcc:
This option will not work on Mac OS X unless all libraries (including libgcc.a) have also been compiled with -static. Since neither a static version of libSystem.dylib nor crt0.o are provided, this option is not useful to most people.
参考自:https://stackoverflow.com/questions/3801011/ld-library-not-found-for-lcrt0-o-on-osx-10-6-with-gcc-clang-static-flag

链接选项-static的作用:
On system that support dynamic linking, this prevents linking with the shared libaries. On other systems, this option has no effect.
关于编译clang和gcc的区别可以参考: 编译器GCC与Clang的异同。

3、解决方案

  在需要链接静态库时,可以直接指定所需要链接静态库的路径,比如

LDFLAGS += $(LIB_DIR)/$(LIB_NAME).a

注意事项:
1、 如果系统的搜索路径下同时存在静态链接库和动态链接库,默认情况下会链接动态链接库。如果需要强制链接静态链接库,需要加上"-satic"选项。但是对于MacOSX系统,不能指定"-static"选项时,可以直接指定所需要链接静态库的路径。
2、Mac OSX系统下查看可执行文件链接的动态库:

otool -arch x86_64 -L ./demo

3、linux下查看可执行文件链接的动态库:

ldd ./demo
4、参考

https://www.v2ex.com/t/407074
https://stackoverflow.com/questions/3801011/ld-library-not-found-for-lcrt0-o-on-osx-10-6-with-gcc-clang-static-flag


THE END

转载于:https://www.cnblogs.com/SoaringLee/p/10532359.html

你可能感兴趣的:(c/c++,操作系统)