# 包含外部Makefile
include ./../../../linux.mk

ProjectName        := FTU_cfg_parse


DIR := $(realpath $(CURDIR)/..)
LAST_DIR := $(notdir $(DIR))


# 可执行文件目标
OutputFile         := $(EXE_REL)/$(ProjectName)
MakeDirCommand     := mkdir -p

# 静态库链接（注意顺序很重要，被依赖的库放在后面）
# Libs               := -lcom_channel -lcom_scan -liec -lself_ptl -lfunc -ltask -lcomm -lshell -lpthread 
Libs               :=  -lxml -lcJSON 
LibPath            := -L $(ROOT_DIR)/lib -L $(LIB_REL) 

# 链接选项
LinkOptions        := -O0 -Wl,--as-needed # --as-needed 只链接实际用到的库

OBJ := $(DIR)/$(ProjectName)/obj
SRC := $(SRC_ROOT_DIR)/$(LAST_DIR)/$(ProjectName)/src
INC := $(SRC_ROOT_DIR)/$(LAST_DIR)/$(ProjectName)/inc

# 定义源文件和对象文件
SOURCES     := $(wildcard $(SRC)/*.c) $(wildcard $(SRC)/*.cpp)
OBJECTS     := $(patsubst $(SRC)/%.c, $(OBJ)/%.o,$(filter %.c,$(SOURCES))) 
OBJECTSCPP  := $(patsubst $(SRC)/%.cpp, $(OBJ)/%.o,$(filter %.cpp,$(SOURCES))) 

ALL_OBJECTS := $(OBJECTS) $(OBJECTSCPP)

# 编译选项
APP_C_FLAGS := $(C_FLAGS)
APP_C_FLAGS += -I $(INC) -g

# 如果是静态链接，添加静态链接标志
# STATIC_FLAGS := -static  # 完全静态链接（包含libc等）
STATIC_FLAGS := -static-libgcc -static-libstdc++  # 只静态链接gcc相关库



# 链接标志
LDFLAGS = $(LibPath) $(Libs) $(LinkOptions) $(STATIC_FLAGS)

# LDFLAGS += -Wl,--undefined=_shell_command_start,--undefined=_shell_command_end

# 伪目标
.PHONY : all clean veryclean rebuild

# 默认目标
all: $(OutputFile)

# 构建可执行文件
$(OutputFile): $(ALL_OBJECTS)
	@$(MakeDirCommand) $(dir $@)
	$(CPP) -o $@ $^ $(LDFLAGS)
	@if [ -f "$@" ]; then \
		echo "Build successful: $@"; \
		# 显示文件信息 \
		file $@; \
		# 显示链接的库 \
		echo "Linked libraries:"; \
		ldd $@ 2>/dev/null || echo "(static binary)"; \
	fi

# 重新构建
rebuild: veryclean all

# 清理
clean:
	rm -f $(OBJ)/*.o
	rm -f $(OBJ)/*.d
	rm -f $(OutputFile)
	rm -f ./out/*.*

# 非常彻底的清理
veryclean: clean
	rm -f ./out/$(OutputFile)
	rm -f $(SRC)/*.bak
	rm -f $(INC)/*.bak

# C对象文件规则
$(OBJECTS): $(OBJ)/%.o: $(SRC)/%.c 
	@mkdir -p $(dir $@)
	$(CC) $(APP_C_FLAGS) -o $@ -c $<

# C++对象文件规则
$(OBJECTSCPP): $(OBJ)/%.o: $(SRC)/%.cpp 
	@mkdir -p $(dir $@)
	$(CPP) $(APP_C_FLAGS) -o $@ -c $<

# 可选：自动生成依赖
DEP_FILES := $(ALL_OBJECTS:.o=.d)

-include $(DEP_FILES)

# 生成依赖文件
$(OBJ)/%.d: $(SRC)/%.c
	@mkdir -p $(dir $@)
	$(CC) $(APP_C_FLAGS) -MM -MT '$(OBJ)/$*.o' $< > $@

$(OBJ)/%.d: $(SRC)/%.cpp
	@mkdir -p $(dir $@)
	$(CPP) $(APP_C_FLAGS) -MM -MT '$(OBJ)/$*.o' $< > $@

.DELETE_ON_ERROR: