MacOS 下的动态链接

本文主要讲解 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 中引用的外部符号在一个动态库(动态库中保存由其到处的符号信息)中,此时链接器并不会对该符号进行重定位,而是标记其为动态链接符号,把真正的链接过程保留到装载时执行。

image.png

如果存在未定义符号,编译链接时一样是会报错的。

这时候,可以利用本文 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<
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值