# Makefile for libhello shared library
# Builds libhello.lib as an ELF shared object (ET_DYN).

# Target architecture.
ARCH := x86_64

# Toolchain
TOOLCHAIN_PREFIX := $(shell cd ../../.. && pwd)/toolchain/local/bin/x86_64-elf-
CXX := $(TOOLCHAIN_PREFIX)g++
LD := $(TOOLCHAIN_PREFIX)ld
NM := $(TOOLCHAIN_PREFIX)nm
STRIP := $(TOOLCHAIN_PREFIX)strip

# Compiler flags: freestanding, no stdlib
# Build as PIC so the final ET_DYN image can be relocated by the kernel loader.
override CXXFLAGS := \
    -std=gnu++20 \
    -g -O2 -pipe \
    -Wall \
    -Wextra \
    -nostdinc \
    -ffreestanding \
    -fno-stack-protector \
    -fno-stack-check \
    -fPIC \
    -fno-rtti \
    -fno-exceptions \
    -ffunction-sections \
    -fdata-sections \
    -m64 \
    -march=x86-64 \
    -mno-80387 \
    -mno-mmx \
    -mno-red-zone \
    -mcmodel=small \
    -I ../../include \
    -isystem ../../include/libc \
    -isystem ../../include/montauk \
    -isystem ../../include/gui \
    -isystem ../../../kernel/freestnd-c-hdrs/x86_64/include \
    -isystem ../../../kernel/freestnd-cxx-hdrs/x86_64/include

# Linker flags for a bare-metal ELF shared object.
override LDFLAGS := \
    -shared \
    --build-id=none \
    --hash-style=sysv \
    -m elf_x86_64 \
    -z max-page-size=0x1000

# Output
OUTDIR := ../../bin/os
LIBNAME := libhello
LIBSRC := src/libhello.cpp

.PHONY: all clean

all: $(OUTDIR)/$(LIBNAME).lib

$(OUTDIR):
	mkdir -p $@

src/libhello.o: src/libhello.cpp Makefile | $(OUTDIR)
	$(CXX) $(CXXFLAGS) -c src/libhello.cpp -o $@

src/stb_truetype_impl.o: src/stb_truetype_impl.cpp Makefile | $(OUTDIR)
	$(CXX) $(CXXFLAGS) -c src/stb_truetype_impl.cpp -o $@

$(OUTDIR)/$(LIBNAME).lib: src/libhello.o src/stb_truetype_impl.o
	rm -f $(OUTDIR)/$(LIBNAME).lib.sym
	$(LD) $(LDFLAGS) src/libhello.o src/stb_truetype_impl.o -o $@

clean:
	rm -rf ../../bin/os/$(LIBNAME).lib ../../bin/os/$(LIBNAME).lib.sym src/libhello.o src/stb_truetype_impl.o
