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
于是得到了 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
然后运行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
于是得到了 hellod.dll 这么一个动态链接库
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的错误,程序无法正常运行。
有网友问到了如果程序里面同时用到了静态链接库和动态链接库 ,那该怎么办呢?其实很简单,还是以上贴的程序为例子,我们已经得到了静态库libhellos.a和动态库libhellod.sa ,我们现在修改一下主程序同时调用它们,如下
/* main.c */
#include <stdio.h>
#include "hellos.h"
#include "hellod.h"
main() {
char* text = "Hello World!/n";
printS(text);
printD(text);
}
编译链接:
gcc -o hello main.c hellod.dll libhellos.a
然后运行hello
print in static way: Hello World!
print in dynamic way: Hello World!
此时删掉libhellos.a,仍然能正常运行。如果删掉hellod.dll则会报找不到hellod.dll的错误。细心的读者可能注意到了,这次编译的命令和前面有点不一样,这是因为gcc自己会判断是动态库还是静态库(但如果这个库不在当前目录的话,必须指定全路径 ) ,然后自动采取了相应的编译策略。