【问题标题】:hint the dynamic library dependencies in the archive file提示归档文件中的动态库依赖关系
【发布时间】:2018-10-09 22:55:06
【问题描述】:

在我的 c/c++ 混合项目中,我正在构建各个文件夹的源文件,将它们与 ar 一起归档到它们自己的 .a 文件中,然后在最后阶段将它们全部链接在一起。到现在为止还挺好。我的问题是,是否可以在 ar 阶段暗示任何动态库依赖项,因此不必在链接阶段明确指定它们?

我的意思是,如果一个组件依赖于 pthread 并且最终的二进制文件需要链接到它,可能是动态的,它可以不将此依赖项添加到存档中,以便稍后由链接器解决吗?

使用链接器而不是ar 来创建部分链接的对象而不是存档是否会提供任何此类工具来提示在最终链接阶段满足动态库依赖关系?

【问题讨论】:

  • ar 实际上只是一个将多个文件连接成一个文件的工具,并允许您提取它们,可能带有索引。它不是一个对 C++ 或 C 构建过程或动态库一无所知的工具。
  • @NeilButterworth 是的,我很感激。因此,我更倾向于选择在归档/elf 标头中的某个部分添加一些内容,然后由链接器对其进行解析和处理。有点像编译器将 -Wl 之后的内容传递给链接器,而不必理解它的含义。
  • 修改标题?在构建阶段(甚至可能不会生成 .elf)?请检查[SO]: How to create a Minimal, Complete, and Verifiable example (mcve),然后将您认为遇到的问题减少为可回答的问题。
  • 如果您小心的话,共享库允许您传递该信息;静态库没有。如果您想要方便,请使用共享库。如果您不能使用共享库,我相信您将不得不接受不便知道要链接哪些其他库,而无法以编译器/链接器可以使用的方式将其记录在存档库文件中。跨度>
  • 此链接kaizou.org/2015/01/linux-libraries 提供了对不同选项和后果的非常详细的全方位解释。

标签: c++ c gcc dynamic-library unix-ar


【解决方案1】:

您可以使用 GNU ar 的“l”选项。
正如手册页所说:

l   Specify dependencies of this library.  The dependencies must immediately
    follow this option character, must use the same syntax as the
    linker command line, and must be specified within a single argument.
    I.e., if multiple items are needed, they must be quoted to form
    a single command line argument.  For example
    L "-L/usr/local/lib -lmydep1 -lmydep2"

ar 将此数据存储在成员“__.LIBDEP”中,该成员嵌入在 .a 文件中,可以通过 ar p mylib.a __.LIBDEP 访问

$ cat static_lib_test.c

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/syscall.h>
#include <unistd.h>

_Noreturn void *start(void *arg)
{
    fprintf(stderr, "child (%d) won!\n", gettid());
    syscall(SYS_exit_group, EXIT_SUCCESS);
}

int main(int argc, const char *argv[])
{
    pthread_t thread;
    if (pthread_create(&thread, NULL, start, (void *) 0) < 0)
    {
        fprintf(stderr, "error: unable to create new thread\n");
        exit(EXIT_FAILURE);
    }
    fprintf(stderr, "Race begin!\n");
    fprintf(stderr, "parent (%d) won!\n", gettid());
    syscall(SYS_exit_group, EXIT_SUCCESS);
}

编译:
$ gcc -Wall -c static_lib_test.c -o static_lib_test.o
存档:
$ ar rcvsl "-L/usr/lib -lpthread" static_lib_test.a static_lib_test.o
链接:
$ gcc $(ar p static_lib_test.a __.LIBDEP | tr '\0' '\n') -o static_lib_test static_lib_test.a
示例运行:$ ./static_lib_test

Race begin!
parent (13547) won!

测试于:Linux arch 5.11.13-zen1-1-zen、GNU ar (GNU Binutils) 2.36.1

【讨论】:

    猜你喜欢
    • 2010-12-27
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 2011-08-14
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多