gcc库

GCC库生成

动态库和静态库编译使用

main.c

1
2
3
4
5
6
7
8
#include <stdio.h>
#include "max.h"
int main(int argc, char *argv[])
{
int a = 10, b = -2, c = 100;
printf("max among 10, -2 and 100 is %d.\n", max(a, b, c));
return 0;
}

max.c

1
2
3
4
5
6
7
8
9
#include "stdio.h"
int max(int n1, int n2, int n3)
{
int max_num = n1;
max_num = max_num < n2? n2: max_num;
max_num = max_num < n3? n3: max_num;
printf("\nlib test makefile add path\n");
return max_num;
}

max.h

1
2
3
4
#ifndef __MAX_H__
#define __MAX_H__
int max(int n1, int n2, int n3);
#endif

makefile

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.PHONY: build test clean

max.o: max.c
gcc -c -fPIC $<
#动态库
build1: max.o
gcc -o libmax.so -shared max.o
test1: main.c build1
gcc -o dynamic $< -L./ -Wl,-rpath=./ -lmax
#静态库
build2:max.o
ar -rcs libmaxs.a max.o
test2: main.c build2
gcc -o static $< -L ./ -lmaxs

clean:
rm -f *.o *.so *.a

gcc常用编译选项:

选项 含义
-static 链接静态库,禁止使用动态库
-shared 进行动态库编译,链接动态库
-Ldir 在库的搜索路径中增加dir目录
-lname 链接静态库(libname.a)或动态库(libname.so)的库文件
-fPIC(或fpic) 生成使用相对地址无关的目标代码
-Wl,-rpath=dir 指定动态库文件位置
-->

请我喝杯咖啡吧~

支付宝
微信