1.编写test1.c文件
7. 编写test_main.c,包含main函数,实现调用
8. 编写Makefile,实现静态库被调用
9. 在终端执行make,生成可执行文件testmain,终端执行:./testmain
11. 注意将.so文件添加到 /user/lib目录下,否则动态库不能被调用到!
#include "test1.h"
int add(int a, int b)
{
return a+b;
}
2.编写test1.h文件
#ifndef _TEST1_H
#define _TEST1_H
int add(int a, int b);
#endif
3. 编写test2.c文件
#include<stdio.h>
#include "test1.h"
#include "test3.h"
void print_add(int a, int b)
{
printf("test2:%d %d\n",add(a,b), sub(a,b));
}
4. 编写test2.h文件
#ifndef _TEST2_H
#define _TEST2_H
void print_add(int a, int b);
#endif
5. 编写test3.c文件
#include "test3.h"
int sub(int a,int b)
{
return a-b;
}
6. 编写test3.h文件
#ifndef _TEST3_H
#define _TEST3_H
int sub(int a,int b);
#endif
7. 编写test_main.c,包含main函数,实现调用
#include "test1.h"
#include "test2.h"
#include "test3.h"
void main()
{
print_add(10,56);
}
8. 编写Makefile,实现静态库被调用
all: test1.o test3.o test2.o test_main.o creat_liba testmain clean
creat_liba:
@echo "start creat static libxxx.a"
ar cr libtest1.a test1.o test2.o
ar cr libtest3.a test3.o
@echo "Finish creat libxxx.a"
testmain:
export LD_LIBRARY_PATH=$(LD_LIBRARY_PATH):/mnt/ao_so_demo
gcc test_main.c -L. -ltest1 -ltest3 -o testmain
test1.o: test1.c test1.h
gcc -c test1.c
test3.o: test3.c test3.h
gcc -c test3.c
test2.o: test2.c test1.h
gcc -c test2.c
test_main.o:test_main.c test1.h test2.h
gcc -c test_main.c
clean:
rm -rf *.o
rm -rf *.a
clean_TARGET:
rm -rf testmain
9. 在终端执行make,生成可执行文件testmain,终端执行:./testmain
运行结果:
test2:66 -46
10. 编写动态库,实现动态库调用静态库,并生成可执行文件testmain
all: test1.o test3.o test2.o test_main.o creat_liba creat_libso testmain clean
creat_liba:
@echo "start creat static libxxx.a"
ar cr libtest.a test1.o test3.o
@echo "Finish creat libxxx.a"
creat_libso:
@echo "start creat so"
gcc -shared test2.o -L. -ltest -o libtest2.so
@echo "Finish creat so"
testmain:
export LD_LIBRARY_PATH=$(LD_LIBRARY_PATH):/mnt/ao_so_demo
gcc test_main.c -L. -ltest2 -o testmain
test1.o: test1.c test1.h
gcc -c test1.c
test3.o: test3.c test3.h
gcc -c test3.c
test2.o: test2.c test1.h
gcc -c -fPIC test2.c
test_main.o:test_main.c test1.h test2.h
gcc -c test_main.c
clean:
rm -rf *.o
rm -rf *.a
11. 注意将.so文件添加到 /user/lib目录下,否则动态库不能被调用到!