# makefile makefile 完整教學 http://maxubuntu.blogspot.com/2010/02/makefile.html #mipi bridge ```c= #usage: make main OR make CC = gcc #欲使用的C compiler //CFLAGS = -O3 -ansi #欲使用的參數 //INC = -I /usr/foo/include #include headers的位置 //LIB = -L /usr/foo/lib #include libraries的位置 main: main.o foo1.o ${CC} main.o foo1.o ${CFLAGS} ${INC} ${LIB} -o main main.o: main.c target.h ${CC} main.c ${CFLAGS} ${INC} ${LIB} -lpthread -c foo1.o: foo1.c target.h ${CC} foo1.c ${CFLAGS} ${INC} ${LIB} -c clean: @rm -rf *.o ``` </br> #電流量測 ```cmake #usage: make main OR make CC = gcc #欲使用的C compiler //CFLAGS = -O3 -ansi #欲使用的參數 //INC = -I /usr/foo/include #include headers的位置 //LIB = -L /usr/foo/lib #include libraries的位置 main: main.o current_hal.o ads8861.o acf2101.o mux506.o ${CC} main.o foo1.o -o main main.o: main.c current_hal.h ${CC} main.c -c current_hal.o: current_hal.c current_hal.h ${CC} current_hal.c -c ads8861.o: ads8861.c ads8861.h current_hal.h ${CC} ads8861.c -c acf2101.o: acf2101.c acf2101.h current_hal.h ${CC} acf2101.c -c mux506.o: mux506.c mux506.h current_hal.h ${CC} mux506.c -c clean: @rm -rf *.o ``` 下面才是電流量測完整通用的makefile ```cmake #usage: make main OR make CC := gcc #欲使用的C compiler CFLAGS := -g -c #CFLAGS = -O3 -ansi #欲使用的參數 #INC = -I /usr/foo/include #include headers的位置 #LIB = -L /usr/foo/lib #include libraries的位置 SRC := $(wildcard *.c) OBJS := $(patsubst %.c, %.o, $(SRC)) all: main libintegrator.so main: main.c $(CC) main.c -o $@ -ldl libintegrator.so: $(OBJS) $(CC) -shared $(OBJS) -o $@ -lbcm2835 %.o: %.c $(CC) -fPIC $(CFLAGS) -o $@ $< .PHONY: clean clean: rm libintegrator.so main $(OBJS) ``` 上面的例子來說明 **wildcard** 和 **patsubst** **wildcard** 表示瀏覽資料夾內的檔案 **patsubst** 表示瀏覽資料夾內的檔案,並替換 SRC := $(wildcard *.c) OBJS := $(patsubst %.c, %.o, $(SRC)) SRC的右側使用的wildcard是make所提供的函式,會把和其引數符合的檔名展開。$(wildcard *.c)在現階段,會展開為ex : main.c a.c b.c d.c OBJS的右側使用變數的替換規則,生成把SRC中的.c換成.o的目的檔。SRC為main.c a.c b.c d.c,所以OBJS會是main.o a.o b.o d.o 另外放上x098的makefile ```cmake CC := gcc CFLAGS := -g -c SRCS := $(wildcard *.c) #OBJS := $(patsubst %.c, %.o, $(SRC)) OBJS := (SRCS:.c=.o) all: x098 x098: $(OBJS) $(CC) $(SRC) -o $@ -lbcm2835 %.o: %.c $(CC) $(CFLAGS) -o $@ $< .PHONY:clean clean: rm -f x098 $(OBJS) ``` </br> 如果修改過任何檔案,清除編譯出來的目的檔 執行檔 ```cmake make clean ``` 編譯 ```cmake make ``` 執行編譯出的執行檔 x098 ```cmake sudo ./x098 ```