免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1381 | 回复: 0
打印 上一主题 下一主题

GCC静态链接与动态链接(转) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-07-24 17:37 |只看该作者 |倒序浏览
  传说中的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
#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
#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)即可。
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/73786/showart_1090979.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP