经典C语言的makefile

时间:2022-06-02 15:26:05

----------------------------------------------------------------

1.适用于最简单的全部都在一个文件夹里

----------------------------------------------------------------

TARGET = server
LIBS = 
CC = gcc
CFLAGS = -g -Wall


.PHONY: default all clean


default: $(TARGET)
all: default


OBJECTS = $(patsubst %.c, %.o, $(wildcard *.c))
HEADERS = $(wildcard *.h)


%.o: %.c $(HEADERS)

$(CC) $(CFLAGS) -c $< -o $@



.PRECIOUS: $(TARGET) $(OBJECTS)


$(TARGET): $(OBJECTS)

$(CC) $(OBJECTS) -Wall $(LIBS) -o $@



clean:
-rm -f *.o
-rm -f $(TARGET)


-----------------------------------------------------------------------------------





-----------------------------------------------------------------------------------

2.按照目录结构生成可执行文件和.o文件

/project

--------/bin        (存放可执行文件)

--------/obj        (存放.o文件)

--------/source (存放.h文件和.c文件) 

------------------------------------------------------------------------------------


DIR_BIN = ../bin
DIR_OBJ = ../obj


TARGET = server
BIN_TARGET = $(DIR_BIN)/$(TARGET)


LIBS = 
CC = gcc
CFLAGS = -g -Wall


.PHONY: default all clean


default: $(BIN_TARGET)
all: default


OBJECTS = $(patsubst %.c,  $(DIR_OBJ)/%.o, $(wildcard *.c))
HEADERS = $(wildcard *.h)


$(DIR_OBJ)/%.o: %.c $(HEADERS)
$(CC) $(CFLAGS) -c $< -o $@


.PRECIOUS: $(BIN_TARGET) $(OBJECTS)


$(BIN_TARGET): $(OBJECTS)
$(CC) $(OBJECTS) -Wall $(LIBS) -o $@


clean:
-rm -f $(DIR_OBJ)/*.o
-rm -f $(BIN_TARGET)




---------------------------------------------------------------------------------------------------