现在的位置: 首页 > 综合 > 正文

GCC静态链接与动态链接[转]

2012年12月02日 ⁄ 综合 ⁄ 共 1246字 ⁄ 字号 评论关闭

以前转过一篇gcc的使用,那个是对比vc来比较的,太长了,再转个简单的~

转自:http://blogger.org.cn/blog/more.asp?name=jkit&id=12170

 传说中的GCC神功盖世,威力无比,今日一见,果然不同凡响。拿出收藏了多年的HelloWorld牛刀小试,于是心悦诚服。

看代码:
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 hellod.dll 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的错误,程序无法正常运行。

至此,GCC小发神威,轻松就让我们领略了静态链接和动态链接的威力。对了还没说环境呢,以上程序在WindowsXP sp2,gcc version 3.4.4 (mingw special) 下通过。如果想在linux下面试,只需要把生成的动态库的名字换一下(hellod.dll ==〉libhellod.so)即可。

抱歉!评论已关闭.