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

---------- 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/p/2643356.html