一个简单可复用的makefile

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名称;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值