linux---静态库与动态库的创建、生成、使用

来源:互联网 发布:linux cp命令文件夹 编辑:程序博客网 时间:2024/05/19 02:42

静态库,以.a为后缀,直接编译到程序中。

动态库,以.so.xx.xx命名,间接引用 。

系统库函数的基本路径是

/lib

/usr/lib

/usr/local/lib


创建静态库


-rw-r--r-- 1 test developer 66 7月  20 11:28 libhello.c
-rw-r--r-- 1 test developer 72 7月  20 11:27 libhello.h

[test@localhost tt]$ cat libhello.c
#include<stdio.h>
void print_hello(void)
{
        printf("hello \n");
}

[test@localhost tt]$ cat libhello.h
#ifndef __libhello_H_
#def __libhello_H_
void print_hello(void);
#endif

[test@localhost tt]$ gcc -c libhello.c
[test@localhost tt]$ ll
总用量 12
-rw-r--r-- 1 test developer   66 7月  20 11:28 libhello.c
-rw-r--r-- 1 test developer   72 7月  20 11:27 libhello.h
-rw-r--r-- 1 test developer 1008 7月  20 11:29 libhello.o


使用ar创建静态库

r 把目标文件包含在库中,替换任何已经在档案中存在的同名目标文件

c 如果目标文件不存在,则默认创建该库

s 维护映射符号名到目标文件的表格


[test@localhost tt]$ ar rc libhello.a libhello.o
[test@localhost tt]$ ls
libhello.a  libhello.c  libhello.h  libhello.o
[test@localhost tt]$


使用静态库

[test@localhost tt]$ cat usehello.c
#include"libhello.h"
int main()
{
        print_hello();
        return 0;
}


gcc -o usehello_static usehello.c libhello.a


[test@localhost tt]$ ./usehello_static
hello
[test@localhost tt]$




创建共享库

[test@localhost tt]$ ls
libhello.c  libhello.h  usehello.c


[test@localhost tt]$ gcc -fPIC -Wall -g -c libhello.c
[test@localhost tt]$ ls
libhello.c  libhello.h  libhello.o  usehello.c
[test@localhost tt]$

-fPIC  参数生成与位置无关

-W 去除所有警告

编译共享库

[test@localhost tt]$ gcc -g -shared -Wl,-soname,libhello.so.1.0 -o libhello.so.1.0 libhello.o -lc
[test@localhost tt]$ ls
libhello.c  libhello.h  libhello.o  libhello.so.1.0  usehello.c
[test@localhost tt]$

-lc 引用c库

-shared 构建共享库

 -Wl 将后面的 -soname,libhello.so.1.0 传递共享库

-soname 说明其soname 为libhello.so.1.0


[test@localhost tt]$ ln -sf libhello.so.1.0 libhello.so
[test@localhost tt]$ ls
libhello.c  libhello.h  libhello.o  libhello.so  libhello.so.1.0  usehello.c
[test@localhost tt]$

使用共享库

[test@localhost tt]$ gcc -Wall -g -c usehello.c -o usehello.o
[test@localhost tt]$ gcc -g -o usehello_dynamic usehello.o -L ./ -lhello
[test@localhost tt]$ ls
libhello.c  libhello.o   libhello.so.1.0  usehello_dynamic
libhello.h  libhello.so  usehello.c       usehello.o
[test@localhost tt]$


[test@localhost tt]$ LD_LIBRARY_PATH=$(pwd) ./usehello_dynamic
hello
[test@localhost tt]$

如何不使用-Ldirectory标识

可以采用以下任何一种方法

第一种

把此库复制到/usr/lib 或者/lib文件夹中 ,或者在此两个文件夹任意一个创建一个快捷方式 并命名为libname.so

第二种

将共享文件的路径添加到 /etc/ld.so.conf  每行增加一个路径,完成后运行ldconfig



静态库与共享库之间的区别

在执行文件时,不需要查找静态库

当多个进程使用同一个共享库,比较好。共享库节约了系统内存,发现错误,只需要修改库文件



















原创粉丝点击