linux常用的makefile模版編寫

2021-06-19 15:06:34 字數 2607 閱讀 4053

在linux下面,我們不得不自己寫makefile,makefile的確博大精深,但是實際上對於日常的使用來說,無非就是

1:編譯可執行程式。2:編譯lib庫 3:編譯so庫

本博針對上面三種目的各自寫出了makefile模版,希望對大家有所幫助。

一.編譯可執行程式

當前目錄下制定檔案編譯成可執行檔案(連線外部庫的話只需要更改inc和lib即可)

cxx = g++

target = bitmaploctest

c_flags +=

-g -wall

lib_flags =

-pthread

all: $(target)

bitmaploctest: bitmaploctest.o bitmaploc.o file_lock.o

$(cxx) -o $@ $^ $(lib_flags) $(lib) $(c_flags)

.cpp.o:

$(cxx) -c -o $*.o $(inc) $(c_flags) $*.cpp

.cc.o:

$(cxx) -c -o $*.o $(inc) $(c_flags) $*.cc

clean:

-rm -f *.o $(target)

二.編譯成lib庫

當前目錄下指定檔案編譯成lib庫(一般lib庫在編譯的時候不會將使用的外部庫編譯進來,而是等編譯成可執行程式時或者.so時)

inc_dir= ./

src_dir= ./

obj_dir= ./

lib_dir= ./

h_dir= ./

obj_ext= .o

cxxsrc_ext= .cpp

csrc_ext= .c

lib_ext= .a

h_ext= .h

objects = $(obj_dir)bitmaploc$(obj_ext) \

$(obj_dir)file_lock$(obj_ext)

lib_target = $(lib_dir)libbitmaploc$(lib_ext)

$(obj_dir)%$(obj_ext): $(src_dir)%$(cxxsrc_ext)

@echo

@echo 「compiling $<

==> $@…」

$(cxx) $(inc) $(c_flags) -c $<

-o $@

$(obj_dir)%$(obj_ext): $(src_dir)%$(csrc_ext)

@echo

@echo 「compiling $<

==> $@…」

$(cc) -i./ $(inc) $(c_flags) -c $<

-o $@

all:$(lib_target)

$(lib_target): $(objects)

all: $(objects)

@echo

$(ar) rc $(lib_target) $(objects)

@echo 「ok」

clean:

rm -f $(lib_target) $(objects)

三.編譯成so庫

當前目錄下指定檔案編譯成so庫(必須將所有引用的外部庫都編譯進來)

cc = gcc

cxx = g++

cflags  =

-wall -pipe -ddebug -d_new_lic -g -d_gnu_source -shared -d_reentrant

lib     =

-lconfig -ldl -lrt -l../../lib -lttc -g

include =

-i../spp_inc

oo    = service.o tinystr.o tinyxml.o tinyxmlerror.o tinyxmlparser.o uin_conf.o stat.o

targets = ../../lib/libranch.so

all: $(targets)

stat:tool_stat.cpp

$(cxx) $(include) tool_stat.cpp -o tool_stat stat.o tinystr.o tinyxml.o tinyxmlerror.o tinyxmlparser.o -g

cp tool_stat ../../bin

$(targets): $(oo)

$(cxx) $(cflags) $(include) $(oo) -o $@ $(libdir) $(lib)

.c.o:

$(cc)  $(cflags) -c $(include) $<

echo $@

.cpp.o:

$(cxx) $(cflags) -c $(include) $<

echo $@%:

%.c$(cc) $(cflags) -o $@ $< $(oo) $(ldflags)

echo $@

clean:

rm -f *.o

rm -f $(targets)

rm -f tool_stat

ok,我常用的makefile也就這三種格式,希望對大家有用。

linux核心可載入模組的makefile

在開發linux核心驅動時,免不了要接觸到makefile的編寫和修改,儘管網上的makefile模板一大堆,做一些簡單的修改就能用到自己的專案上,但是,對於這些基礎的東西,更應該做到知其然並知其所以然。本篇文章中只討論linux核心模組編譯的makefile,linux核心makefile總覽可以...

Linux核心開發 最簡單的Makefile

最簡單的linux驅動程式 至少需要乙個makefile,乙份源 本文簡單解釋makefile中的各個make target的意義。這裡只是介紹乙個簡單的基礎的makefile,生產環境需要更好的makefile模板和構建工具。示例 obj m helloword.o pwd shell pwd k...

Linux下C語言程式設計基礎 Makefile

假設我們有下面這樣的乙個程式,源 如下 main.c include mytool1.h include mytool2.h int main int argc,char argv mytool1.h ifndef mytool 1 h define mytool 1 h void mytool1 ...