linux下编译工程需要用到makefile,这里先上一个简单可满足基本需要的,后续再补充。
#支持的编译产物类型,当前支持exe-应用程序,lib-静态库,dll-动态库
target_type = exe
#指定编译器,编译选项
compiler = gcc
cflags := -O2 -Wall -pthread -w -fPIC -fpermissive
#cflags += -std=c++11
ifneq ($(target_type), exe)
cflags += -msse4
endif
ifeq ($(target_type), dll)
cflags += -ldl -Wl,-soname,libtest.so
endif
#通过宏来控制编译的源程序
#cflags += -DDEBUG
#输出产物(makefile有自动推导功能,识别一个.o文件,就会自动将.c或.cpp文件加在依赖关系中)
objs := a.o b.o
ifeq ($(target_type), exe)
target = ./test
else ifeq ($(target_type), lib)
target = ./test.a
else
target = ./libtest.so.1.0.0.0
endif
#添加依赖
include_path = -I ./ -I ../../
#libc.a libd.a
dep_lib = ./libc.a ./lib/libd.a
#libe.so libf.so libg.so
dep_dll = -L ./ -le -lf -L ../../ -lg
#编译过程
%.o : %.cpp
$(compiler) $(cflags) -c -o $@ $^ $(include_path)
$(target) : $(objs)
ifeq ($(target_type), exe)
$(compiler) $(cflags) -o $@ $^ $(dep_lib) $(dep_dll)
else ifeq ($(target_type), lib)
ar cr $@ $(objs) $(dep_lib)
else
$(compiler) $(cflags) -shared -o $@ $^ $(dep_lib) $(dep_dll)
endif
rm -rf $(objs)
#清除产物(有利于重新编译,以防编译失败生成部分.o,所以这里将$(objs)再删除一次)
clean:
rm -rf $(objs) $(target)
几点说明:
1、ifeq和第一个参数之间,要使用空格隔开;
2、在规则后使用ifeq时,要顶格写;
3、执行makefile,可使用make -f my_makefile;执行makefile中的clean,可使用make -f my_makefile clean;
4、如果是dll,可以在dll所在目录,运行命令ldconfig -n .生成makefile中不带版本号的so名称;