GCC静态链接与动态链接

 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自己会判断是动态库还是静态库(但如果这个库不在当前目录的话,必须指定全路径 ,然后自动采取了相应的编译策略。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值