gpt4 book ai didi

c - gcc:链接时替换

转载 作者:太空宇宙 更新时间:2023-11-03 23:38:56 25 4
gpt4 key购买 nike

我目前正在尝试了解 gcc 编译器和链接器是如何工作的。我遇到了一种称为“链接时替换”的技术,我觉得它非常有趣。目标是在多个文件中对一个函数进行多个定义,并在链接时决定将这些定义中的哪些定义进入最终的可执行文件。

一个简单的例子:

主.c:

#include "header.h"

int main(void)
{
hello("everyone");
return 0;
}

标题.h:

#ifndef _HEADER_H
#define _HEADER_H

void hello(const char * name);

#endif

文件1.c:

#include "header.h"
#include <stdio.h>

void hello(const char * name)
{
printf("File1: Hello, %s!\n", name);
}

文件2.c:

#include "header.h"
#include <stdio.h>

void hello(const char * name)
{
printf("File2: Hello, %s!\n", name);
}

现在我有两个问题:

  • 是否可以通过使用适当的链接顺序来选择函数(如果所有三个文件都出现在链接器的参数列表中)?
  • 假设 file2.c 实现了 main.c 需要的许多功能。是否可以使用链接器替换 file1.c(具有相同名称)中不同实现的单个函数或某些函数?链接器应首先使用 file1.c 中的函数定义,然后将 file2.c 用于剩余的未解析函数。

我希望我的问题是可以理解的;)

谢谢!

最佳答案

Is it possible to select a function by using an appropriate linking order (if all three files appear in the linker's argument list)?

如果“所有三个文件”是指目标文件(并假设没有弱符号),则不会:所有 3 个文件都将被链接,您将得到一个重复的符号定义错误。

但是如果你将 file1.o 放入 lib1.a,并将 file2.o 放入 lib2.a,那么是的:

gcc main.c -l1 -l2  # uses file1.o:hello
gcc main.c -l2 -l1 # uses file2.o:hello

更多详情 herehere .

Suppose file2.c implements many functions which are needed by main.c. Is it possible to replace a single function or some functions by different implementations in file1.c (with the same name) by using the linker?

是的,但仅限于支持弱符号的平台(例如 ELF 平台,参见 __attribute__((weak)) here)。

如果 file2.o 中的所有符号都是弱定义的,而 file1.o 中的所有符号都不是,那么链接 file1.o 和 file2.o 将达到预期的结果:强符号获胜。

我相信(但还没有测试过)如果 file1.o 和 file2.o 弱定义相同的符号,那么顺序很重要:

gcc main.c file1.o file2.o  # file1.o definitions override file2.o
gcc main.c file2.o file1.o # file2.o definitions override file1.o

关于c - gcc:链接时替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50871055/

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