1. 共享库
- 在编程中,共享代码文件被称为共享库、共享对象、动态链接库、DLL文件等。
2. 使用共享库
- 生成命令:
ld helloworld-lib.o -o helloworld-lib.out -dynamic-linker /lib/ld-linux.so.2 -lc -m elf_i386
-dynamic-linker /lib/ld-linux.so.2
操作系统将加载程序/lib/ld-linux.so.2,以加载外部库并将其链接到程序。/lib/ld-linux.so.2这样的程序成为动态链接器-lc
链接库c,该库在GNU、Linux系统上的文件名为libc.so,给定库名,在本例中为c(通常不止一个字符),GNU/Linux链接器将字符串lib加至库名之前,将字符串.so加到库名之后,构成库文件名。这个库包含许多函数以自动执行各种任务。我们使用其中两个,即打印字符串的printf和退出程序的exit。
- 关于静态/动态链接可执行文件:
- 未使用共享库的程序称为静态链接
- 使用共享库的程序称为动态链接
- 使用ldd查看链接文件位置
ldd ./helloworld-lib
输出:
linux-gate.so.1 (0xf7fb8000)
libc.so.6 => /lib32/libc.so.6 (0xf7dbf000)
/lib/ld-linux.so.2 (0xf7fb9000)
3. printf
- 原型
int printf(char *string, ...);
- Example
.section .data
firststring:
.ascii "Hello! %s is a %s who loves the number %d\n\0"
name:
.ascii "Jonathan\0"
personstring:
.ascii "person\0"
numberloved:
.long 3
.section .text
.globl _start
_start:
pushl numberloved
pushl $personstring
pushl $name
pushl $firststring
call printf
pushl $0
call exit

- 为什么prinft函数知道一共有多少个参数?该函数会在字符串中搜索,计算一种找到多少%d和%s,接着从栈中抓取相应数目的参数。
4. 构建一个共享库
# 将.o 文件链接为共享库
ld -shared write-record.o read-record.o -o librecord.so
# 动态链接到这个库
ld write-records.o -o write-records.out -L . -dynamic-linker /lib/ld-linux.so.2 -lrecord
# 运行时 设置环境变量
LD_LIBRARY_PATH=.
export LD_LIBRARY_PATH
# then
./write-records.out
3. 其他