« | August 2025 | » | 日 | 一 | 二 | 三 | 四 | 五 | 六 | | | | | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | | | | | | | |
|
|
[C/C++]GCC静态链接与动态链接 |
冥思者 发表于 2006/3/3 11:50:30 |
传说中的GCC神功盖世,威力无比,今日一见,果然不同凡响。拿出收藏了多年的HelloWorld牛刀小试,于是心悦诚服。看代码:1:建静态库
/* hellos.h */#ifndef _HELLO_S_H#define _HELLO_S_Hvoid 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.car 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_Hvoid 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)即可。 | |
|
回复:GCC静态链接与动态链接 |
zhouciming(游客)发表评论于2012/3/8 16:28:08 |
编译静态库时,用你的编译指令不行呀。我的系统是Fedora12,我的makefile为:
main: main.c libhellos.a
2 gcc -o hello main.c -static -L. -lhellos
3
4 libhellos.a: hellos.o
5 ar cqs libhellos.a hellos.o
6
7 hellos.o: hellos.c
8 gcc -c -o hellos.o hellos.c
9
10 #dhello: main.c libhellod.so
11 # gcc -o dhello main.c -L. -lhellod
12 #
13 #libhellod.so: hellos.c
14 # gcc -shared -o libhellod.so hellos.c
15
16 clean:
17 rm -f *.o *.a *.so dhello
编译结果为:
[zcm@t #220]$make
gcc -c -o hellos.o hellos.c
ar cqs libhellos.a hellos.o
gcc -o hello main.c -static -L. -lhellos
/usr/bin/ld: cannot find -lc
collect2: ld 返回 1
make: *** [main] 错误 1
[zcm@t #221]$
| |
|
回复:GCC静态链接与动态链接 |
游客(游客)发表评论于2007/9/26 15:39:37 |
|
|
回复:GCC静态链接与动态链接 |
guest1(游客)发表评论于2007/3/29 15:22:51 |
|
|
回复:GCC静态链接与动态链接 |
秋雁(游客)发表评论于2006/9/6 0:56:44 |
谢谢,帮了大忙了!!!
gcc -o hello main.c -static -L. -lhellos原来gcc的-static、-L、-l等一定要放在后面的呀。 | |
|
回复:GCC静态链接与动态链接 |
snow_man2004(游客)发表评论于2006/9/3 21:55:01 |
兄台,好啊,遇到你真是太及时了,good!写得好!!!! | |
|
回复:GCC静态链接与动态链接 |
flying#(游客)发表评论于2006/4/24 20:50:06 |
|
|
» 1 »
|
|
统计 |
blog名称:长夜慢慢兮,心越来越远! 日志总数:13 评论数量:48 留言数量:1 访问次数:154074 建立时间:2006年3月3日 | |