# =========================
# Makefile for ExcALIBUR Demos
# =========================

CC      := gcc
CXX     := g++

# Library search paths
LDFLAGS := -L../../lib -L../../4000 -L../

# Libraries with potential circular dependencies — wrapped in --start/end-group
LIBS_GROUP := -lExcDiscr -lExc4000 -lexchost2dpr

# System / runtime libraries
LIBS_SYS := -ldl -lrt -lftd2 -lftd3 -pthread

# =========================
# Build configuration
# =========================
# Default: RELEASE build.  Use `make RELEASE=0` for a debug build.
RELEASE ?= 1

ifeq ($(RELEASE),1)
  CFLAGS   := -std=c11 -D_GNU_SOURCE -O2 -g -DNDEBUG -fPIC -Wall -I. -I../../4000 -I..
  CXXFLAGS := -std=c++11 -D_GNU_SOURCE -O2 -g -DNDEBUG -fPIC -Wall -I. -I../../4000 -I..
else
  CFLAGS   := -std=c11 -D_GNU_SOURCE -O0 -g -fPIC -Wall -Wextra -I. -I../../4000 -I..
  CXXFLAGS := -std=c++11 -D_GNU_SOURCE -O0 -g -fPIC -Wall -Wextra -I. -I../../4000 -I..
endif

$(info )
$(info ======================================)
$(info   ExcALIBUR build: $(if $(filter 1,$(RELEASE)),RELEASE,DEBUG))
$(info ======================================)
$(info )

# =========================
# Source and object files
# =========================
SRCS_C   := $(wildcard *.c)
SRCS_CPP := $(wildcard *.cpp)
OBJS_C   := $(SRCS_C:.c=.o)
OBJS_CPP := $(SRCS_CPP:.cpp=.o)
OBJS     := $(OBJS_C) $(OBJS_CPP)
PROGS    := $(SRCS_C:.c=) $(SRCS_CPP:.cpp=)

# =========================
# Default target
# =========================
.PHONY: all clean

all: $(PROGS)
	@echo "=== $(if $(filter 1,$(RELEASE)),RELEASE,DEBUG) build completed successfully ==="

# =========================
# Compile rules
# =========================

# FIX: use CFLAGS (not CPPFLAGS) for C sources;
#      use CXXFLAGS (not CPPFLAGS) for C++ sources.
#      CPPFLAGS is the standard make variable for the C pre-processor,
#      not for C++ compiler flags — mixing them causes -std=c11 to be
#      passed to g++ which produces a warning.
%.o: %.c
	$(CC) $(CFLAGS) -c $< -o $@

%.o: %.cpp
	$(CXX) $(CXXFLAGS) -c $< -o $@

# =========================
# Link rules
# =========================

# FIX: -L flags must have no space between -L and the path
#      ("-L ../../lib" is parsed correctly by gcc but is non-standard
#      and can confuse some toolchains; use "-L../../lib" consistently).
#
# NOTE: C sources are still linked with $(CXX) intentionally —
#       the driver libraries may pull in C++ runtime symbols, so
#       linking with g++ ensures libstdc++ and libgcc_s are included.

$(SRCS_C:.c=): %: %.o
	$(CXX) -o $@ $^ $(LDFLAGS) \
		-Wl,--start-group $(LIBS_GROUP) -Wl,--end-group \
		$(LIBS_SYS)

$(SRCS_CPP:.cpp=): %: %.o
	$(CXX) -o $@ $^ $(LDFLAGS) \
		-Wl,--start-group $(LIBS_GROUP) -Wl,--end-group \
		$(LIBS_SYS)

# =========================
# Clean
# =========================
clean:
	rm -f $(OBJS) $(PROGS)
