linux - 动态链接尝试全部产生静态链接的二进制文件?为什么?

标签 linux gcc shared-libraries

我正在按照本教程转到“T”here关于在 Linux 中创建动态链接的共享库,当我按照说明操作时,gcc 似乎改为静态链接库。

本教程建议使用 3 个文件:foo.cfoo.hmain.c。 Main 包含 foo.h 并调用 foo(),在 foo.c 中定义。

我对调试教程做了一点改动...我的 foo 看起来像这样:

void foo(void) {
    int i = 54321;
    printf( "Shared lib: %d\n", i );
}

它告诉我使用这 3 个步骤进行编译:

gcc -c -Wall -Werror -fpic foo.c
gcc -shared -o libfoo.so foo.o
gcc -L/home/username/foo -Wall -o test main.c -lfoo

当我运行 ./test 时,它起作用了,我可以从 foo() 中看到“hello 54321”。事实上,它工作得很好,如果我删除 libfoo.so,它就可以工作。看起来很可疑,所以我做了 objdump -S test 并在目标文件中找到了这个小家伙:

000000000000068a <foo>:
 68a: 55                    push   %rbp
 68b: 48 89 e5              mov    %rsp,%rbp
 68e: 48 83 ec 10           sub    $0x10,%rsp
 692: c7 45 fc 31 d4 00 00  movl   $0xd431,-0x4(%rbp)
                                   ^^^  there's my constant, 54321, in hex.
                      should be in the "dynamic" object, not here, right?

 699: 8b 45 fc              mov    -0x4(%rbp),%eax
 69c: 89 c6                 mov    %eax,%esi
 69e: 48 8d 3d af 00 00 00  lea    0xaf(%rip),%rdi        # 754 <_IO_stdin_used+0x4>
 6a5: b8 00 00 00 00        mov    $0x0,%eax
 6aa: e8 b1 fe ff ff        callq  560 <printf@plt>
 6af: 90                    nop
 6b0: c9                    leaveq
 6b1: c3                    retq

我做错了什么? 提前谢谢你...

附言使用 版本 gcc (Ubuntu 7.2.0-8ubuntu3.2) 7.2.0

在 x86_64 Debian Stretch 上编译

最佳答案

What am I doing wrong?

你很可能有 libfoo.a/home/username/foo目录。

或者你不小心使用了#include "foo.c"什么时候#include "foo.h"是有意的。

你可以试着找出foo()的定义在哪里正在进入 test与:

gcc -L/home/username/foo -Wall -o test main.c -lfoo -Wl,-y,foo

应该显示对 foo引用来自一些/tmp/xyz.o和来自 <somewhere>定义 .

关于linux - 动态链接尝试全部产生静态链接的二进制文件?为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49808937/

相关文章:

c++ - 段错误和指针问题

linux - Unix 环境中的高级程序设计第 1 版

c++ - 使用其他文件构建 gcc 插件

linux - 安装供应商程序-libpython3.so : cannot open shared object file

c++ - 使用特定 header 部署 C++ 共享库

c++ - 带有 rtkaio 的 linux 上的 aio_write 有时很长

Java 应用程序性能问题

gcc - 版本脚本和隐藏可见性

c++ - 为什么这个依赖名称查找找到的是全局标识符而不是方法?

c - 如何从共享对象中删除符号?