c - 'add an index to an archive file' 是什么意思?

标签 c static-libraries unix-ar

我的 C 教科书使用 -s 命令行选项创建一个存档,该选项将索引添加到以下存档文件。

ar -rcs libfile.a file1.o file2.o

但是,我不明白什么是索引或它的用途?

最佳答案

将评论转化为答案。

ranlib 程序有一段漫长而复杂的历史。基本上,为了使链接器能够有效地扫描库,某些程序——ar 本身或 ranlib——添加了一个特殊的“索引”文件,用于标识定义在定义每个符号的库和目标文件。如果任何保存的文件是目标文件,许多版本的 ar 会自动添加。有些似乎需要使用 -s 选项来刺激。其他人根本不添加索引文件,而是依靠 ranlib 来完成这项工作。

macOS 文档上的ar:

-s — Write an object-file index into the archive, or update an existing one, even if no other change is made to the archive. You may use this modifier flag either with any operation, or alone. Running ar s on an archive is equivalent to running ranlib on it.

很长一段时间以来,我都不需要在 macOS 上显式使用此选项(我也没有运行 ranlib)——我认为情况在千禧年的第一个十年中期的某个时候发生了变化。

Don't object files already come with symbol tables? Wouldn't it seem redundant to add another symbol table to the start of the archive file?

每个目标文件都包含有关该目标文件中内容的信息(以及有关引用对象和已定义对象的信息);存档索引包含更简单的信息,即存档中的哪些目标文件定义了每个符号,因此链接器不必分别扫描存档中的每个目标文件。

So, would it be correct to say that the index at the start of the archive is just a giant symbol table which replaces the individual symbol tables in each object file so the linker has an easier job?

不是取代——是增强。它允许链接器识别将哪个目标文件拉入链接的可执行文件。然后链接器像处理任何其他目标文件一样处理目标文件,检查定义和引用,将新定义的引用标记为已满足并识别以前未使用但尚 undefined reference 。但是链接器不必读取存档中的每个文件来计算文件定义了哪些符号——它从索引文件中知道定义了哪些符号。

To clarify the index allows the linker to find the specific object file which defines a symbol rather than having to scan every object file to resolve a symbol?

是的,没错。

关于c - 'add an index to an archive file' 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57648076/

相关文章:

铛生成文件 "ar: no archive members specified"

c++ - 在 Windows 上使用 Makefile 编译

c - 序列栈和结构体指针

objective-c - 在非 ARC 项目中包含 ARC header

ios - IOS静态库如何运行presentViewController

c++ - 将静态库链接到其他静态库

c - 为什么 C 中没有数组类型的右值?

c - 匹配字符串中的子字符串,容差为 1 个字符不匹配

c++ - 虚幻引擎 4 上的 Websockets?

c++ - 外部符号如何解析?