一、gcc生成静态库和动态库
1.编辑生成例子程序hello.h、hello.c、main.c
代码:
hello.h
#ifndef HELLO_H
#define HELLO_H
void hello(const char *name);
#endif//HELLO_H
hello.c
#include<stdio.h>
void hello(const char *name)
{
printf(“Hello %s\n”,name);
}
main.c
#include"hello.h"
int main()
{
hello(“everyone”);
return 0;
}
2.将hello.c文件编译成.o文件
3.由.o 文件创建静态库并使用
ar -crv libmyhello.a hello.o
使用静态库
gcc main.c libmyhello.a -o hello.o
4.由.o文件创建使用动态库文件
使用动态库
有错误解决办法:是找不到动态库文件 libmyhello.so。程序在运行时, 会在/usr/lib 和/lib 等目录中查找需要的动态库文件。若找到,则载入动态库,否则将提 示类似上述错误而终止程序运行。我们将文件 libmyhello.so 复制到目录/usr/lib下就可以了
sudo mv libmyhello.so /usr/lib
二、静态库.a与.so库文件的生成与使用.pdf
1.创建文件写入代码
A1.c
A2.c
A.h
test.c
2.静态库.a文件的使用和生成
2.1生成目标文件.o
2.2生成静态库.a文件
2.3使用.a库文件创建可执行程序
gcc -o test test.c libafile.a
./test
3.共享库.so文件的生成和使用
3.1生成目标文件.o
3.2生成共享库.so文件
gcc -shared *.o -o libsofile.so
gcc -o test test.c libsofile.so
./test
三、静态库和动态库两者比较
gcc编译得到.o文件 gcc -c hello.c
创建静态库 ar -crv libmyhello.a hello.o
创建动态库 gcc -shared -fPIC -o libmyhello.so hello.o
使用库生成可执行文件 gcc -o hello main.c -L. -lmyhello
执行可执行文件 ./hello,当静态库和动态库同时存在的时候,程序会优先使用动态库。
lo.c
创建静态库 ar -crv libmyhello.a hello.o
创建动态库 gcc -shared -fPIC -o libmyhello.so hello.o
使用库生成可执行文件 gcc -o hello main.c -L. -lmyhello
执行可执行文件 ./hello,当静态库和动态库同时存在的时候,程序会优先使用动态库。