# 定义编译器
CC = ccarm

# 定义编译选项，例如开启警告、优化级别等
CFLAGS = -Owholeprogram

# 定义目标文件
TARGET = myprogram
BUILD_DIR = build
BIN_DIR = bin

# 定义源文件和目标文件
SRCS = $(wildcard *.c)
OBJS_OK = $(patsubst %.c,$(BUILD_DIR)/%.ok.o,$(SRCS))
OBJS_NG = $(patsubst %.c,$(BUILD_DIR)/%.ng.o,$(SRCS))
INFS_OK = $(patsubst %.c,$(BUILD_DIR)/%.ok.inf,$(SRCS))
Qnormalize_FLAG = $(BUILD_DIR)/ghs_qnormalize

# 默认目标
all: clean $(BIN_DIR) OK NG

# 在构建目标文件和目标程序之前，确保目录存在
$(INFS_OK) $(OBJS_OK) $(OBJS_NG): | $(BUILD_DIR)
$(TARGET): | $(BIN_DIR)

# 构建目标程序 依赖不同
NG: $(OBJS_NG)
	@echo "Linking target (NG): $@"
	$(CC) $(CFLAGS) -o $(BIN_DIR)/$@ $(OBJS_NG)

OK: $(INFS) $(Qnormalize_FLAG) $(OBJS_OK)
	@echo "Linking target (OK): $@"
	$(CC) $(CFLAGS) -o $(BIN_DIR)/$@ $(OBJS_OK)
	@echo " ------ build success ------\n\n"

# 构建目标文件
$(BUILD_DIR)/%.ok.inf: %.c
	@echo "Handling $<"
	$(CC) $(CFLAGS) -c $< -o $@ -Q

$(Qnormalize_FLAG): $(INFS_OK)
	@echo "Running -Qnormalize"
	$(CC) $(CFLAGS) $(INFS_OK) -Qnormalize
	touch $@
	
$(BUILD_DIR)/%.ok.o: %.c $(INFS_OK) $(Qnormalize_FLAG)
	@echo "Compiling $<"
	$(CC) $(CFLAGS) -c $< -o $@ $(INFS_OK) -Qfinal

$(BUILD_DIR)/%.ng.o: %.c
	@echo "Compiling $<"
	$(CC) $(CFLAGS) -c $< -o $@

# 确保目录存在
$(BUILD_DIR) $(BIN_DIR):
	@echo "Creating directory: $@"
	mkdir -p $@

clean:
	@echo "Cleaning up..."
	rm -rf $(BUILD_DIR) $(BIN_DIR) $(TARGET)


# 打印帮助信息
help:
	@echo "Makefile Usage:"
	@echo "  make NG       - Simulate an operation that fails to compile"
	@echo "  make OK       - Demonstrates successful compilation operations"
	@echo "  make clean    - Clean up compilation results"
	@echo "  make help     - Display this help message"
	@echo "  make all      - Build all targets (OK and NG)"
	@echo "you check the whole operation by adding options '-ni'"