gpt4 book ai didi

c++ - gcc关于嵌套依赖项的共享库 “undefined reference”

转载 作者:行者123 更新时间:2023-12-02 10:16:27 27 4
gpt4 key购买 nike

g++ 5.4.0

Ubuntu 16.04

我有几个共享库,这是它们的抽象:

libtest0.so: definition of `void foo()`
libtest1.so: `extern void foo()`, and not depends on libtest0.so
libtest2.so: use libtest1.so and depends on libtest1.so

现在我有一个二进制文件:

a.out: use libtest2.so

当然 a.out具有未定义的 foo()符号。为了解决这个问题,我尝试了:

g++ main.cc -L. -ltest2 -ltest0

因为libtest0.so具有 foo()的定义。

但是,它不起作用:

$g++ -g main.cc -L. -ltest2 -ltest0
libtest1.so: undefined reference to `foo'
collect2: error: ld returned 1 exit status

我的问题是:
  • 为什么会发生此“ undefined reference ”?
  • 是否可以告诉链接程序libtest0.so具有foo()的定义的解决方案?

  • 谢谢。

    Update1:​​

    如果我在编译libtest2时链接libtest0,则编译:

    g++ -g main.cc -L. -ltest2

    现在一切都很好。但是,在现实世界中,我无法更改libtest2.so的链接

    更新2

    clang++与此cmd一起使用:(链接器是ld,不是lld)

    # clang version 11.0.0
    clang++ -g main.cc -L. -ltest2 -ltest0

    Update3

    一个示例是: https://gist.github.com/xgwang/da93edcc06542264157f600eb64bc082

    只需在Linux上对其进行重击即可。已在Ubuntu 16。

    最佳答案

    首先,引用here(重点是我的话):

    Failure in final linking, undefined symbols

    This is the most common error that happens while using --as-needed. It happens during the final linking stage of an executable (libraries don't create problems, because they are allowed to have undefined symbols). The executable linking stage dies because of an undefined symbol that is present in one of the libraries fed to the command line. However, the library is not used by the executable itself, thus it gets removed by --as-needed. This usually means that a library was not linked to another library, but was using it, and then relying on the final executable to link them together. This behavior is also an extra encumbrance on developers using that library because they have to check for the requirements.



    解决方法,而不是

    g++ main.cc -L. -ltest2 -ltest0

    尝试

    g++ main.cc -L. -ltest2 -Wl,--no-as-needed -ltest0

    禁用 --as-needed行为。

    最适合我的最小示例:

    #!/bin/bash

    export LD_LIBRARY_PATH=.

    g++ -fPIC -shared test0.cc -o libtest0.so
    g++ -fPIC -shared test1.cc -o libtest1.so
    g++ -fPIC -shared test2.cc -o libtest2.so -L. -ltest1

    g++ main.cc -L. -ltest2 -Wl,--no-as-needed -ltest0

    关于c++ - gcc关于嵌套依赖项的共享库 “undefined reference”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61775728/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com