准备两个文件,以最简单的形式进行展示。
add.c
int add(int x, int y) {
return x + y;
}
main.c
为了方便直接在头文件中声明函数
#include <stdio.h>
extern int add(int, int);
int main() {
int x = 1;
int y = 2;
printf("%d + %d = %d\n", x, y, add(x, y));
}
生成object文件
gcc -c add.c
生成库
采用ar指令进行生成静态库,其中三个参数的含义为:
ar的参数 | |
---|---|
参数c | 创建一个库,不管库是否存在,都将创建。 |
参数s | 创建一个库,不管库是否存在,都将创建。 |
参数r | 在库中插入模块(替换)。默认新的成员添加在库的结尾处,如果模块名已经在库中存在,则替换同名的模块。 |
ar rcs libadd.a add.o
链接操作静动态库一致
gcc main.c -L . -l add
经过测试,windows下为libxxx.a也可以
环境 | 常用命名 |
---|---|
Linux | libxxx.a |
Windows | libxxx.lib |
生成object文件
需要添加-fpic
参数
gcc -c -fpic add.c
生成库
生成一个动态库,有可执行权限
不指定-o的话默认是a.exe/a.out
gcc -shared add.o -o libadd.dll
链接操作静动态库一致
gcc main.c -L . -l add
环境 | 常用命名 |
---|---|
Linux | libxxx.so |
Windows | libxxx.dll |
Linux 静态库和动态库 | 爱编程的大丙 (subingwen.cn)
侵删
Usage: ar [emulation options] [-]{dmpqrstx}[abcDfilMNoOPsSTuvV] [--plugin <name>] [member-name] [count] archive-file file...
ar -M [<mri-script]
commands:
d - delete file(s) from the archive
m[ab] - move file(s) in the archive
p - print file(s) found in the archive
q[f] - quick append file(s) to the archive
r[ab][f][u] - replace existing or insert new file(s) into the archive
s - act as ranlib
t[O][v] - display contents of the archive
x[o] - extract file(s) from the archive
command specific modifiers:
[a] - put file(s) after [member-name]
[b] - put file(s) before [member-name] (same as [i])
[D] - use zero for timestamps and uids/gids (default)
[U] - use actual timestamps and uids/gids
[N] - use instance [count] of name
[f] - truncate inserted file names
[P] - use full path names when matching
[o] - preserve original dates
[O] - display offsets of files in the archive
[u] - only replace files that are newer than current archive contents
generic modifiers:
[c] - do not warn if the library had to be created
[s] - create an archive index (cf. ranlib)
[l <text> ] - specify the dependencies of this library
[S] - do not build a symbol table
[T] - deprecated, use --thin instead
[v] - be verbose
[V] - display the version number
@<file> - read options from <file>
--target=BFDNAME - specify the target object format as BFDNAME
--output=DIRNAME - specify the output directory for extraction operations
--record-libdeps=<text> - specify the dependencies of this library
--thin - make a thin archive
optional:
--plugin <p> - load the specified plugin
emulation options:
No emulation specific options
ar: supported targets: elf64-x86-64 elf32-i386 elf32-iamcu elf32-x86-64 pei-i386 pe-x86-64 pei-x86-64 elf64-l1om elf64-k1om elf64-little elf64-big elf32-little elf32-big pe-bigobj-x86-64 pe-i386 srec symbolsrec verilog tekhex binary ihex plugin
Report bugs to <https://sourceware.org/bugzilla/>