# Makefile for libmath shared library
# Builds libmath.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-sse \
    -mno-sse2 \
    -mno-red-zone \
    -mcmodel=small \
    -I ../../include \
    -isystem ../../include/libc \
    -isystem ../../include/montauk

# 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 := libmath
LIBSRC := src/libmath.cpp

.PHONY: all clean

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

$(OUTDIR)/$(LIBNAME).lib: $(LIBSRC) Makefile
	@mkdir -p $(OUTDIR)
	rm -f $(OUTDIR)/$(LIBNAME).lib.sym
	$(CXX) $(CXXFLAGS) -c $(LIBSRC) -o src/libmath.o
	$(LD) $(LDFLAGS) src/libmath.o -o $@

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