C 语言 静态库和动态库的创建和应用

本文详细介绍了如何使用C语言在Windows和Linux平台上生成动态库和静态库,并通过示例展示了静态链接和动态链接的实现过程。文章包含警告信息解释和生成过程的步骤说明。
---------- GETPI.C
double getPI(void) { return 3.14159265358979324; } ---------- MYLIB.H #ifndef _MYLIB_H_ #define _MYLIB_H_ void say(const char *str); double getPI(void); #endif //_MYLIB_H_ ---------- RUN.BAT @prompt me#$s rem 生成静态库 mylib.a gcc -o say.o -c say.c gcc -o getPI.o -c getPI.c ar rs mylib.a say.o getPI.o del *.o rem 生成 位置无关的动态库 mylib.dll gcc -c -fPIC say.c getPI.c gcc -shared -o mylib.dll say.o getPI.o del *.o rem test.c 静态链接 mylib.a gcc -o static.exe test.c -L. ./mylib.a rem test.c 动态库链接 mylib.dll gcc test.c -o dynamic.exe -L. -lmylib pause ---------- SAY.C #include <stdio.h> void say(const char *str) { puts("\x22\x22\x22\x22\x22\x22\x22\x22\x22\x22\x22\x22"); puts(str); puts("\x22\x22\x22\x22\x22\x22\x22\x22\x22\x22\x22\x22"); } ---------- TEST.C #include <stdio.h> #include "mylib.h" int main(void) { say("hello, world!"); printf("%.16lf", getPI()+1); return 0; }
// windows 平台
--> rem 生成静态库 mylib.a

--> gcc -o say.o -c say.c

--> gcc -o getPI.o -c getPI.c

--> ar rs mylib.a say.o getPI.o

--> del *.o

--> rem 生成 位置无关的动态库 mylib.dll

--> gcc -c -fPIC say.c getPI.c
say.c:1: warning: -fPIC ignored for target (all code is position independent)
getPI.c:1: warning: -fPIC ignored for target (all code is position independent)

--> gcc -shared -o mylib.dll say.o getPI.o

--> del *.o

--> rem test.c 静态链接 mylib.a

--> gcc -o static.exe test.c -L. ./mylib.a

--> rem test.c 动态库链接 mylib.dll

--> gcc test.c -o dynamic.exe -L. -lmylib

--> pause
请按任意键继续. . .

 

// linxu 平台
# 生成静态库 mylib.a
gcc -o say.o -c say.c
gcc -o getPI.o -c getPI.c
ar rs mylib.a say.o getPI.o
rm *.o

# 生成 位置无关的动态库 mylib.so
gcc -c -fPIC say.c getPI.c
gcc -shared -o mylib.so say.o getPI.o
rm *.o


# test.c 静态链接 mylib.a
gcc -o static test.c -L. ./mylib.a

# test.c 动态库链接 mylib.dll
gcc test.c -o dynamic -L. ./mylib.so
pause

 

转载于:https://www.cnblogs.com/mathzzz/archive/2012/08/17/2643356.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值