gpt4 book ai didi

c - 链接器是复制函数的内容还是简单地链接到它?

转载 作者:行者123 更新时间:2023-12-01 23:20:36 24 4
gpt4 key购买 nike

假设我有 fowling C 代码,并且我正在使用 gcc 的 linux 机器上编译它。

测试.c:

#include <stdio.h>

int main() {
printf("hi\n");
return 0;
}

我知道 stdio.h定义 printf printf 的主体存在于 C library 中以二进制格式。

以下是我的问题:
  • 使用 gcc test.c 进行正常编译时, 链接器是否动态链接到 printf还是静态链接?
  • printf 最终生成 write()系统调用。链接器是否复制定义的 C 库 printf到最终的可执行文件(最终将在运行时调用 write())还是复制 write()直接在最终的可执行文件中结束。

  • 或者换句话说:
    如果我打开可执行文件并转成 ascii 格式,我会在其中看到“printf()”还是“write()”?
  • 如果我编译我的代码然后卸载 C lib我的代码还会运行吗?自 printf不再在任何地方定义。
  • 最佳答案

    1. When doing a normal compile with gcc test.c, does the linker make a dynamic link to printf or a static link?


    这取决于。给定那个特定的编译命令,如果 C 库的动态版本可用,并且如果 GCC 是为使用它而构建的(两者都很有可能),那么 GCC 将执行动态链接。如果只有静态版本的 C 库可用,或者默认情况下 GCC 构建或配置为静态链接,则将执行静态链接。

    1. printf ultimately makes a write() system call. Is the linker copying the C lib defined printf over to the final executable (which will end up calling write() at runtime) or is it copying write() over in the final executable directly.


    如果 GCC 正在执行静态链接,那么它将直接或间接复制程序所需的所有功能,也可能将其他功能复制到最终的二进制文件中。我特别不确定 GNU 链接器,但有些链接器将在最终二进制文件中包含整个目标库。

    1. If I compile my code and then uninstall the C lib will my code still run? since printf isn't defined anywhere anymore.


    如果您将 C 库静态链接到您的程序中,则之后删除 C 库不会(直接)阻止您的程序运行。但是根据详细信息,它可能会阻止其他所有内容运行,包括 GUI、您的其他应用程序,甚至是 shell,从而提出了这个问题。

    静态链接所有必需的库是最小化二进制文件的运行时依赖项的合理技术,这可以提高与不同于构建环境的系统的兼容性。然而,这确实会产生更大的二进制文件。在任何情况下,除非您以这种方式构建每个程序,否则事后删除库通常不是可行的替代方案。

    关于c - 链接器是复制函数的内容还是简单地链接到它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54906594/

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