动态库和静态库的编译和使用简介

1、代码举例:

(1)main.c

#include <stdio.h>

extern void test_print(void);

int main(void)
{
        test_print();
        return 0;
}

(2)print.c

#include <stdio.h>

void test_print(void)
{

        printf("test!\n");
}

2、静态库方式编译:

(1)生成静态库:

mhp0114@08:20:26:test_lib$ gcc -c print.c
mhp0114@08:20:34:test_lib$ ls
main.c  print.c  print.o

mhp0114@08:20:35:test_lib$ ar rc libprint.a print.o
mhp0114@08:20:50:test_lib$ ls
libprint.a  main.c  print.c  print.o

(2)编译链接静态库:

mhp0114@08:21:37:test_lib$ ls -l
总用量 30
-rwxrwxrwx 1 root root 1652 Sep 29 08:20 libprint.a
-rwxrwxrwx 1 root root 8672 Sep 29 08:21 main
-rwxrwxrwx 1 root root   96 Sep 29 08:19 main.c
-rwxrwxrwx 1 root root   66 Sep 29 08:34 print.c
-rwxrwxrwx 1 root root 1504 Sep 29 08:20 print.o

(3)执行:

mhp0114@08:37:00:test_lib$ ./main
test!

 

3、动态库方式编译:

(1)生成动态库:

mhp0114@08:21:39:test_lib$ gcc -fPIC -shared print.c -o libprint.so
mhp0114@08:22:57:test_lib$ ls
libprint.a  libprint.so  main  main.c  print.c  print.o

(2)编译链接动态库:

mhp0114@08:23:26:test_lib$ gcc main.c -o main1 -L. -lprint
mhp0114@08:36:58:test_lib$ ls -l
总用量 30
-rwxrwxrwx 1 root root 1652 Sep 29 08:20 libprint.a
-rwxrwxrwx 1 root root 8120 Sep 29 08:22 libprint.so
-rwxrwxrwx 1 root root 8672 Sep 29 08:21 main
-rwxrwxrwx 1 root root 8592 Sep 29 08:23 main1
-rwxrwxrwx 1 root root   96 Sep 29 08:19 main.c
-rwxrwxrwx 1 root root   66 Sep 29 08:34 print.c
-rwxrwxrwx 1 root root 1504 Sep 29 08:20 print.o

(3)执行:

mhp0114@08:41:13:test_lib$ ./main1
./main1: error while loading shared libraries: libprint.so: cannot open shared object file: No such file or directory
mhp0114@08:41:15:test_lib$ export LD_LIBRARY_PATH=./
mhp0114@08:41:25:test_lib$ ./main1
test!

动态库编译的生成物需要致命动态库路径,如上export LD_LIBRARY_PATH=./

 

4、查看可执行文件的依赖库

Linux下查看可执行文件依赖的动态库

方法一:

mhp0114@08:43:34:test_lib$ objdump -p main1 | grep NEEDED
  NEEDED               libprint.so
  NEEDED               libc.so.6

方法二:

mhp0114@08:41:26:test_lib$ ldd main1
        linux-vdso.so.1 =>  (0x00007ffcff3a9000)
        libprint.so => ./libprint.so (0x00007f6feb762000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f6feb398000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f6feb964000)

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页