Makfile链接动态库并编译
这里主要是自己写的一个动态库链接版的makefile,比较简单,复杂的我也不会,哈哈哈
CC=GCC
CFLAGS = -Wall -fPIC -o
TARGET = libmytest.so
MYOBJS = test_main.o
MYTARGET= test_main
OBJS = libmytest.o
SRCS = libmytest.c
$(MYTARGET):$(TARGET) $(MYOBJS) //从这行开始
$(CC) -o $(MYTARGET) $(MYOBJS) -lmytest // 5.gcc -o test_main test_main.o -lmytest
$(MYOBJS):
$(CC) -c test_main.c // 4.gcc -c test_main.c 这步生成test_main.o
$(TARGET):$(OBJS)
$(CC) -shared -o $(TARGET) $(OBJS) // 2. gcc -shared -o libmytest.so libmytest.o
cp $(TARGET) /usr/lib // 3. 把生成的动态库文件放在 /usr/lib目录下
$(OBJS):$(SRCS)
$(CC) $(CFLAGS) $(OBJS) -c $(SRCS) // 1.gcc -Wall -fPIC -o libmytest.o -c libmytest.c
clean:
rm *.o $(TARGET) $(OBJS)
开始介绍了,我这总共就只有三个文件,写的有点多,请见谅
test_main.c libmytest.c libmytest.h
我们要把libmytest.c 制作成动态库 ,正常命令为 gcc -Wall -fPIC -shared libmytest.c -o libmytest.so
而在Makefile中 要分为两步来做 分别为
gcc -Wall -fPIC -o libmytest.o -c libmytest.c
gcc -shared -o libmytest.so libmytest.o
即 上面代码段 1 2步 之后编译分两种情况
1 再把libmytest.so复制到/usr/lib , gcc -o test_main.c -lmytest
2 直接编译 gcc -o test_main test_main.c ./libmytest.so ,后面是之前生成动态库的路径
这是命令行实现流程
下面讲下我写的Makfile
Makefile先找到
第一行
$(MYTARGET):$(TARGET) $(MYOBJS)
test_main 是我的最终目标文件, $(TARGET) $(MYOBJS)是我的依赖文件 ,即libmytest.so和libmytest.o
所以继续往下找到,因为$(TARGET)在前面所以先找到他,
$(TARGET):$(OBJS)
知道了之后要$(TARGET) 依赖文件为$(OBJS)
继续找$(OBJS)
$(OBJS):$(SRCS)
$(SRCS)是我们的依赖文件,即libmytest.c
直接执行
$(CC) $(CFLAGS) $(OBJS) -c $(SRCS) //1.gcc -Wall -fPIC -o libmytest.o -c libmytest.c
$(OBJS) 生成了,即可执行
$(CC) -shared -o $(TARGET) $(OBJS) // 2. gcc -shared -o libmytest.so libmytest.o
cp $(TARGET) /usr/lib // 3. 把生成的动态库文件放在 /usr/lib目录下
动态库$(TARGET)弄好了,test_main 还需要 $(MYOBJS)
执行
$(CC) -c test_main.c // 4.gcc -c test_main.c 这步生成test_main.o
$(MYOBJS) 即test_main.o也有了
最后就剩下
$(CC) -o $(MYTARGET) $(MYOBJS) -lmytest // 5.gcc -o test_main test_main.o -lmytest
直接生成test_main文件
Makefile 写好啦, 直接make