A-A+

linux环境下同时使用静态库、动态库编译程序

2017年12月25日 Linux, Makefile, 操作系统 暂无评论 阅读 279 次

因某些原因,有时会需要同时使用静态库及动态库编译代码,这时候我们就必须要了解些下面几个编译参数了。

编译参数

-Wl,-Bstatic

-Wl,-Bdynamic

-Wl,–as-needed

参数定义

-Wl,option

Pass option as an option to the linker. If option contains commas, it is split into multiple options at the commas. You can use this syntax to pass an argument to the option. For example, -Wl,-Map,output.map passes -Map output.map to the linker. When using the GNU linker, you can also get the same effect with -Wl,-Map=output.map.

-Wl,-Bstatic

-Wl,-Bdynamic

   -Bdynamic
   -dy
   -call_shared
       Link against dynamic libraries.  This is only meaningful on platforms for which shared libraries are supported.  This option is normally the default on such platforms.  The different variants of this option are for compatibility with various systems.  You may use this option multiple times on the command line: it affects library searching for -l options which follow it.

   -Bstatic
   -dn
   -non_shared
   -static
       Do not link against shared libraries.  This is only meaningful on platforms for which shared libraries are supported.  The different variants of this option are for compatibility with various systems.  You may use this option multiple times on the command line:
        it affects library searching for -l options which follow it.  This option also implies --unresolved-symbols=report-all.  This option can be used with -shared.  Doing so means that a shared library is being created but that all of the library's external references must be   resolved by pulling in entries from static libraries.

–as-needed 只给用到的动态库设置DT_NEEDED。

 --as-needed
   --no-as-needed
       This option affects ELF DT_NEEDED tags for dynamic libraries mentioned on the command line after the --as-needed option.   Normally the linker will add a DT_NEEDED tag for each dynamic library mentioned on the command line, regardless of whether the library is actually needed or not.  --as-needed causes a DT_NEEDED tag to only be emitted for a library that at that point in the link satisfies a non-weak undefined symbol reference from a regular object file or, if the library is not found in the DT_NEEDED lists of other libraries, a non-weak undefined symbol reference from another dynamic library.  Object files or libraries appearing on the command line after the library in question do not affect whether the library is seen as needed.  This is similar to the rules for extraction of object files from archives.  --no-as-needed restores the default behaviour.

使用实例

LDFLAGS += -Wl,-Bstatic -lmystaticlib
LDFLAGS += -Wl,-Bdynamic -lpthread -lrt -lmydynamiclib
LDFLAGS += -Wl,--as-needed

常见错误打印

确定指定好了链接库目录,但是始终提示找不到相应的动态库,但是静态库没有问题,可能有如下提示:

arm-linux/bin/ld.bfd: cannot find -lmylib

这种情况在排查没有指定库目录的情况下就需要检查下是不是静态库和动态库混合编译没有指定相应的参数。

给我留言