From b64c82ec928dcd9dbd1f5bf4fcd4dfe422647f49 Mon Sep 17 00:00:00 2001
From: MadMaurice <madmaurice@zom.bi>
Date: Mon, 28 Aug 2023 21:56:54 +0200
Subject: [PATCH] Improve build system and add support for tests

---
 Makeconf           |  2 +-
 Makefile           | 33 +++++++++++++++++++++++++++++----
 main.c             |  4 ++++
 tests/test_bus.cpp | 15 +++++++++++++++
 4 files changed, 49 insertions(+), 5 deletions(-)
 create mode 100644 main.c
 create mode 100644 tests/test_bus.cpp

diff --git a/Makeconf b/Makeconf
index deb6dd6..08a2572 100644
--- a/Makeconf
+++ b/Makeconf
@@ -4,6 +4,6 @@ modules := memory/mem_device \
            cpu/cpu \
            cpu/decoder
 
-modules += test
+tests := test_bus
 
 CXX_FLAGS := -I $(CURDIR)
diff --git a/Makefile b/Makefile
index 4ce61c1..0bec760 100644
--- a/Makefile
+++ b/Makefile
@@ -1,10 +1,35 @@
 include Makeconf
 
-$(info $(modules))
-objs := $(addsuffix .o,$(modules))
+emu-objs := $(addsuffix .o,$(modules))
+test-targets := $(patsubst %,tests/%.bin, $(tests))
+
+clean-objs := $(emu-objs) $(test-targets) libemu.a vgbc
+
+.PHONY: all test clean
+
+all: vgbc $(test-targets)
+
+clean:
+	rm -rf $(clean-objs)
+
+test: $(test-targets)
+	@for test in $(tests); do \
+		if ./tests/$$test.bin; then \
+			echo "-- $$test successful"; \
+		else \
+			echo "-- $$test failed"; \
+			exit 1; \
+		fi \
+	done
 
 %.o: %.cpp
 	g++ $(CXX_FLAGS) -c -o $@ $^
 
-vgbc: $(objs)
-	g++ -o $@ $^
+libemu.a: $(emu-objs)
+	ar -rc $@ $^
+
+tests/%.bin: tests/%.cpp libemu.a
+	g++ $(CXX_FLAGS) -o $@ $^
+
+vgbc: main.c libemu.a
+	g++ $(CXX_FLAGS) -o $@ $^
diff --git a/main.c b/main.c
new file mode 100644
index 0000000..d123e09
--- /dev/null
+++ b/main.c
@@ -0,0 +1,4 @@
+int main(int argc, char** argv)
+{
+  return 0;
+}
diff --git a/tests/test_bus.cpp b/tests/test_bus.cpp
new file mode 100644
index 0000000..e66289d
--- /dev/null
+++ b/tests/test_bus.cpp
@@ -0,0 +1,15 @@
+#include <iostream>
+#include "memory/bus.h"
+#include "memory/ram.h"
+
+int main(int argc, char** argv)
+{
+  RAM r(0x1000);
+  Bus b;
+
+  b.map_device(0x0000, 0x0FFF, &r);
+  b.map_device(0x2000, 0x2FFF, &r);
+
+  b.write8(0x60, 42);
+  return (b.read8(0x2060) == 42) ? 0 : 1;
+}