本文主要讲解 MacOS 下的链接,是与 MacOS 和 iOS 开发相关的内容,其他平台可能也会有类似的操作。
本文大部分篇幅都是讲动态链接,静态链接也简单讲了一下,很多不错的参考文章列在文末,感兴趣可以看下。
1、ld manual
Libraries
A static library (aka static archive) is a collection of .o files with a table of contents that lists the global symbols in the .o files. ld will only pull .o files out of a static library if needed to resolve some symbol reference. Unlike traditional linkers, ld will continually search a static library while linking. There is no need to specify a static library multiple times on the command line.
A dynamic library (aka dylib or framework) is a final linked image. Putting a dynamic library on the command line causes two things: 1) The generated final linked image will have encoded that it depends on that dynamic library. 2) Exported symbols from the dynamic library are used to resolve references.
Both dynamic and static libraries are searched as they appear on the command line.
2、动态链接
2.1、动态库符号查找
链接器发现 program1.o 中引用的外部符号在一个动态库(动态库中保存由其到处的符号信息)中,此时链接器并不会对该符号进行重定位,而是标记其为动态链接符号,把真正的链接过程保留到装载时执行。

如果存在未定义符号,编译链接时一样是会报错的。
这时候,可以利用本文 2.4 介绍的方法,把符号查找推迟给 dyld 查找。
2.2、案例
通过例子来分析:
// add.h
extern int add(int num);
// add.c
#include "add.h"
int add(int num){
return num + 8;
}
// main.c
#include"add.h"
int main(){
int tmp = 10;
tmp = add<

最低0.47元/天 解锁文章
4万+

被折叠的 条评论
为什么被折叠?



