写在前面:最近因为需要在不同版本的linux上运行编译后的文件,经常会遇到找不到需要的链接库文件的问题,后来突然想起了静态编译这一说。 1:建静态库 /* hellos.h */ #ifndef _HELLO_S_H #define _HELLO_S_H void printS(char* str); #endif /* hellos.c */ #include "hellos.h" void printS(char* str) { printf("print in static way: %s", str); } 输入命令: gcc -c -o hellos.o hellos.c ar cqs libhellos.a hellos.o //ar是生成库的命令,cqs是参数, libhellos.a是生成的静态链接库须以lib开头,hellos是库名,a表示是静态链接库,hellos.o是刚才生成目标文件。于是得到了libhellos.a这么一个静态链接库
2:主程序 /* main.c */ #include <stdio.h> #include "hellos.h"
main() { char* text = "Hello World!\n"; printS(text); }
编译链接: gcc -o hello main.c -static -L. –lhellos 下面是关于上面命令的解释: 库依赖 使用-I参数可以向gcc的头文件搜索路径中添加新目录。 gcc hello.c -I /home/wuzhiguo/include -o hello 使用-L参数可以向gcc的库文件搜索路径中添加新目录。 gcc hello.c -L /home/wuzhiguo/lib -l mylib -o hello -l mylib 是指示gcc去链接库文件libmylib.so。Linux下的库文件有一个约定,全部以lib开头,因此可以省去lib。 动态库:.so结尾,在运行时加载。 静态库:.a结尾,在编译时加载。 默认gcc优先加载动态库,可以在通过-static选项强制使用静态链接库。 gcc hello.c -L /home/wuzhiguo/lib -static -l mylib -o hello 所以-L后面的点为当前目录,-l后面是要静态连接的库(libhellos.a)
然后运行hello可以看到输出 print in static way: Hello World! 删除libhellos.a和hellos.*后, 程序仍然正常运行。
下面再来看动态链接 3:建动态库 /* hellod.h */ #ifndef _HELLO_D_H #define _HELLO_D_H void printD(char* str); #endif /* hellod.c */ #include "hellod.h" void printD(char* str) { printf("print in dynamic way: %s", str); } 输入命令: gcc -shared -o libhellod.so hellod.c 于是得到了libhellod.so这么一个动态链接库,然后复制到/lib目录中,否则运行的时候找不到库文件。
4:主程序 /* main.c */ #include <stdio.h> #include "hellod.h" main() { char* text = "Hello World!\n"; printD(text); }
编译链接: gcc -o hello main.c -L. -lhellod 然后运行hello可以看到输出 print in dynamic way: Hello World! 如果这时候删除刚刚生成的hellod.dll,再运行则会报告一个找不到hellod.dll的错误,程序无法正常运行。 |
|