# SPDX-License-Identifier: MIT
# chirpmodem C library and tools: quick in-tree build (CMake is the installable one).
#
#   make            libchirpmodem.a, libchirpmodem.so, cm_tx, cm_rx, cm_txvec, cm_rxvec, tests, example
#   make test       conformance (../tools/check_c.py) + the API tests
#   make clean
#
# The tools land here in c/, where the Python scripts look for them.
CC ?= cc
CXX ?= c++
CFLAGS ?= -O2 -march=native -Wall -Wextra
CXXFLAGS ?= -O2 -Wall -Wextra
CPPFLAGS += -std=c99 -D_DEFAULT_SOURCE -Iinclude -Isrc
LDLIBS = -lm

VER = 0.1.0
SOVER = 0

LIBSRC = src/cm_util.c src/cm_ldpc.c src/cm_codec.c src/cm_frame.c src/cm_fft.c src/cm_rx.c \
         src/cm_stream.c src/cm_tx.c
LIBOBJ = $(LIBSRC:.c=.o)
TOOLS = cm_tx cm_rx cm_txvec cm_rxvec
TESTS = tests/test_api tests/test_cpp examples/loopback

all: libchirpmodem.a libchirpmodem.so $(TOOLS) $(TESTS)

# library objects: position independent, only the public API exported
src/%.o: src/%.c src/cm.h include/chirpmodem.h
	$(CC) $(CPPFLAGS) -DCHIRPMODEM_BUILDING $(CFLAGS) -fPIC -fvisibility=hidden -c -o $@ $<
src/cm_ldpc.o: src/ldpc_tables.h

libchirpmodem.a: $(LIBOBJ)
	$(AR) rcs $@ $^

libchirpmodem.so.$(VER): $(LIBOBJ)
	$(CC) $(CFLAGS) -shared -Wl,-soname,libchirpmodem.so.$(SOVER) -o $@ $^ $(LDLIBS)
libchirpmodem.so: libchirpmodem.so.$(VER)
	ln -sf $< libchirpmodem.so.$(SOVER)
	ln -sf $< $@

# tools link the static library, so they run from here without installing
tools/%.o: tools/%.c include/chirpmodem.h src/cm.h
	$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $<
cm_tx: tools/cm_tx_main.o libchirpmodem.a
	$(CC) $(CFLAGS) -o $@ $^ $(LDLIBS)
cm_rx: tools/cm_rx_main.o libchirpmodem.a
	$(CC) $(CFLAGS) -o $@ $^ $(LDLIBS)
cm_txvec: tools/cm_txvec.o libchirpmodem.a
	$(CC) $(CFLAGS) -o $@ $^ $(LDLIBS)
cm_rxvec: tools/cm_rxvec.o libchirpmodem.a
	$(CC) $(CFLAGS) -o $@ $^ $(LDLIBS)

# tests: the C one against the shared library (as an application would link
# it), the C++ one checks the header compiles and links as C++
tests/test_api: tests/test_api.c libchirpmodem.so
	$(CC) -std=c99 -D_DEFAULT_SOURCE -Iinclude $(CFLAGS) -o $@ $< -L. -lchirpmodem -lpthread $(LDLIBS) \
	    -Wl,-rpath,'$$ORIGIN/..'
examples/loopback: examples/loopback.c libchirpmodem.so
	$(CC) -std=c99 -Iinclude $(CFLAGS) -o $@ $< -L. -lchirpmodem $(LDLIBS) -Wl,-rpath,'$$ORIGIN/..'
tests/test_cpp: tests/test_cpp.cpp libchirpmodem.so
	$(CXX) -std=c++11 -Iinclude $(CXXFLAGS) -o $@ $< -L. -lchirpmodem -Wl,-rpath,'$$ORIGIN/..'

test: all
	@test -f ../vectors/index.json || ../tools/make_vectors.py
	../tools/check_c.py
	./tests/test_api
	./tests/test_cpp
	./examples/loopback

clean:
	rm -f src/*.o tools/*.o libchirpmodem.a libchirpmodem.so libchirpmodem.so.* $(TOOLS) $(TESTS)

.PHONY: all test clean
