Linux下静态库.a与.so库文件的生成与使用

编辑四个文件:A1.c  A2.c  A.h test.c

A1.c:

#include <stdio.h>

void print1(int arg){
printf("A1 print arg:%d\n",arg);
}

A2.c:

#include <stdio.h>

void print2(char *arg){
printf("A2 printf arg:%s\n", arg);
}

A.h

#ifndef A_H
#define A_H
void print1(int);
void print2(char *);
#endif

test.c:

#include <stdlib.h>
#include "A.h"

int main(){
print1(1);
print2("test");
exit(0);
}


1、静态库.a文件的生成与使用。

1.1、生成目标文件(xxx.o)

---> gcc -c A1.c A2.c


1.2、生成静态库.a文件

---> ar crv libafile.a A1.o A2.o



1.3、使用.a库文件,创建可执行程序(若采用此种方式,需保证生成的.a文件与.c文件保存在同一目录下,即都在当前目录下)

---> gcc -o test test.c libafile.a

---> ./test


2、共享库.so文件的生成与使用

2.1、生成目标文件(xxx.o)(此处生成.o文件必须添加"-fpic"(小模式,代码少),否则在生成.so文件时会出错)

---> gcc -c -fpic A1.c  A2.c

2.2、生成共享库.so文件

---> gcc -shared *.o -o libsofile.so

2.3、使用.so库文件,创建可执行程序

---> gcc -o test test.c libsofile.so

---> ./test

发现出现错误:

./test: error while loading shared libraries: libsofile.so: cannot open shared object file: No such file or directory

运行ldd test,查看链接情况

ldd test
    linux-vdso.so.1 =>  (0x00007fff0fd95000)
    libsofile.so => not found
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f937b5de000)
    /lib64/ld-linux-x86-64.so.2 (0x0000563f7028c000)


发现确实是找不到对应的.so文件。

这是由于linux自身系统设定的相应的设置的原因,即其只在/lib and /usr/lib下搜索对应的.so文件,故需将对应so文件拷贝到对应路径。

--->sudo cp libsofile.so /usr/lib

再次执行./test,即可成功运行。

---> ./test


同时可直接使用gcc -o test test.c -L. -lname,来使用相应库文件

其中,

        -L.:表示在当前目录下,可自行定义路径path,即使用-Lpath即可。

      -lname:name:即对应库文件的名字(除开lib),即若使用libafile.a,则name为afile;若要使用libsofile.so,则name为sofile)。


猜你喜欢

转载自blog.csdn.net/lisayh/article/details/79726249