ih4cku / blog

deprecated, Git issues are great for writing blogs :)
2 stars 0 forks source link

Makefile tips #84

Open ih4cku opened 7 years ago

ih4cku commented 7 years ago

static pattern rules

References

ih4cku commented 7 years ago

eliminate duplicated words

$(shell echo $(dir $(OBJS)) | xargs -n1 | sort -u)
ih4cku commented 7 years ago

predefined rules

OUTPUT_OPTION = -o $@
COMPILE.c = $(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c
LINK.o = $(CC) $(LDFLAGS) $(TARGET_ARCH)
LINK.c = $(CC) $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH)

%: %.o
    $(LINK.o) $^ $(LDLIBS) -o $@

%.o: %.c
    $(COMPILE.c) $(OUTPUT_OPTION) $<

%: %.c
    $(LINK.c) $^ $(LDLIBS) -o $@
ih4cku commented 7 years ago

order-only prerequsites

there are 2 kinds of prerequisites:

References

ih4cku commented 7 years ago

my template

PROJECT := main

INC_DIR := include
SRC_DIR := src
BUILD_DIR := build
BIN_DIR := bin

BIN := $(BIN_DIR)/$(PROJECT)

CPPFLAGS := -I$(INC_DIR)
CXXFLAGS := -std=c++11 -O2

SRCS := $(shell find $(SRC_DIR) -name '*.cpp')
OBJS := $(patsubst $(SRC_DIR)/%.cpp,$(BUILD_DIR)/%.o,$(SRCS))
DEPS := $(patsubst $(SRC_DIR)/%.cpp,$(BUILD_DIR)/%.dpp,$(SRCS))

.PHONY: all run clean 

all: $(BIN) 

run: $(BIN)
    $(BIN)

$(BIN): $(OBJS) | bin_dir
    $(CXX) $(LDFLAGS) $^ $(LDLIBS) -o $@

$(OBJS): $(BUILD_DIR)/%.o: $(SRC_DIR)/%.cpp | build_dir
    $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $<

$(DEPS): $(BUILD_DIR)/%.dpp: $(SRC_DIR)/%.cpp | build_dir
    $(CXX) -MM $(CPPFLAGS) $< > $@.$$$$; \
    sed 's,\($*\)\.o[ :]*,$(BUILD_DIR)/\1.o $@ : ,g' < $@.$$$$ > $@; \
    rm -f $@.$$$$

build_dir:
    @mkdir -p $(shell echo $(dir $(OBJS)) | xargs -n1 | sort -u | xargs)

bin_dir:
    @mkdir -p $(BIN_DIR)

clean:
    rm -rf $(BIN_DIR) $(BUILD_DIR)

-include $(DEPS)

TODO