linux中创建静态库和动态库

1. 函数库有两种:静态库和动态库。

    静态库在程序编译的时候会被连接到目标代码中,程序运行时将不再需要改静态库。

   动态库中程序编译的时候并不会连接到目标代码中,而是在程序运行时才被载入,因此在程序运行的时候还需要动态库的存在。

程序1: hello.h
#ifndef HELLO_H
#define HELLO_H
void hello(const char *name);
#endif //HELLO_H


程序2: hello.c
#include 
void hello(const char *name)
{
        printf("Hello %s! ", name);
}


程序3: main.c
#include "hello.h"
int main()
{
        hello("everyone");
        return 0;
} 

显然直接编译main.c会报错,所以先要生成hello.h的静态库,根据hello.o来生成。

2.创建静态库,.a为后缀名

#gcc -c hello.c

#ar -rc libmyhello.a hello.o 或者 ar cr libmyhello.a hello.o

接着运行

# gcc -o main main.c libmyhello.a 或者 gcc -o main main.c -L. -lmyhello

#./main

hello everyone

删除静态库文件,程序运行正常。

3.创建动态库,扩展名为.so

#gcc -shared -fPIC -o libmyhello.so hello.o

动态库的编译

#gcc -o hello main.c -L. libmyhello.so

#./hello

/hello:error while loading shared libraries: libmyhello.so: cannot open shared object file: No such file or directory
出错了,提示是找不到动态库文件,程序运行时会在/usr/lib下面找这个动态库文件,找不到就会出错。

:可以将库文件拷贝到/usr/lib和目录下,运行即可。


原文地址:https://www.cnblogs.com/dyllove98/p/3230938.html