From 3552b793e3b30f2bba0e77fbda45a86575f4dae6 Mon Sep 17 00:00:00 2001
From: Tavian Barnes <tavianator@tavianator.com>
Date: Sat, 27 Jul 2024 19:01:18 -0400
Subject: build/flags: Infrastructure to detect compiler flag support

Use it to detect -MD -MP support.
---
 build/deps.mk      |  5 +----
 build/flags-if.sh  | 16 ++++++++++++++++
 build/flags.mk     | 20 +++++++++++++++++++-
 build/flags/deps.c |  8 ++++++++
 4 files changed, 44 insertions(+), 5 deletions(-)
 create mode 100755 build/flags-if.sh
 create mode 100644 build/flags/deps.c

diff --git a/build/deps.mk b/build/deps.mk
index a6ea673..b49e592 100644
--- a/build/deps.mk
+++ b/build/deps.mk
@@ -11,8 +11,5 @@ include build/exports.mk
 gen/deps.mk::
 	${MSG} "[ GEN] $@"
 	@printf '# %s\n' "$@" >$@
-	@if build/cc.sh -MD -MP build/empty.c -o gen/.deps.out; then \
-	    printf '_CPPFLAGS += -MD -MP\n'; \
-	fi >>$@ 2>$@.log
-	${VCAT} $@
 	@printf -- '-include %s\n' ${OBJS:.o=.d} >>$@
+	${VCAT} $@
diff --git a/build/flags-if.sh b/build/flags-if.sh
new file mode 100755
index 0000000..098b2d3
--- /dev/null
+++ b/build/flags-if.sh
@@ -0,0 +1,16 @@
+#!/bin/sh
+
+# Copyright © Tavian Barnes <tavianator@tavianator.com>
+# SPDX-License-Identifier: 0BSD
+
+# Add flags to a makefile if a build succeeds
+
+set -eu
+
+FLAGS=$(sed -n '\|^///|{s|^/// ||; s|[^=]*= ||; p}' "$1")
+
+if build/cc.sh "$@" $FLAGS; then
+    sed -n 's|^/// \(.*=.*\)|\1|p' "$1"
+else
+    exit 1
+fi
diff --git a/build/flags.mk b/build/flags.mk
index c50b077..95d5673 100644
--- a/build/flags.mk
+++ b/build/flags.mk
@@ -103,7 +103,11 @@ _LDLIBS := ${LDLIBS} ${EXTRA_LDLIBS} ${_LDLIBS}
 
 include build/exports.mk
 
-gen/flags.mk::
+# Conditionally-supported flags
+AUTO_FLAGS := \
+    gen/flags/deps.mk
+
+gen/flags.mk: ${AUTO_FLAGS}
 	${MSG} "[ GEN] $@"
 	@printf '# %s\n' "$@" >$@
 	@printf '_CPPFLAGS := %s\n' "$$XCPPFLAGS" >>$@
@@ -112,4 +116,18 @@ gen/flags.mk::
 	@printf '_LDLIBS := %s\n' "$$XLDLIBS" >>$@
 	@printf 'NOLIBS := %s\n' "$$XNOLIBS" >>$@
 	@test "${OS}-${SAN}" != FreeBSD-y || printf 'POSTLINK = elfctl -e +noaslr $$@\n' >>$@
+	@cat ${.ALLSRC} >>$@
 	${VCAT} $@
+.PHONY: gen/flags.mk
+
+# The short name of the config test
+SLUG = ${@:gen/%.mk=%}
+# The source file to build
+CSRC = build/${SLUG}.c
+# The hidden output file name
+OUT = ${SLUG:flags/%=gen/flags/.%.out}
+
+${AUTO_FLAGS}::
+	@${MKDIR} ${@D}
+	@build/flags-if.sh ${CSRC} -o ${OUT} >$@ 2>$@.log; \
+	    build/msg-if.sh "[ CC ] ${SLUG}.c" test $$? -eq 0
diff --git a/build/flags/deps.c b/build/flags/deps.c
new file mode 100644
index 0000000..1c8c309
--- /dev/null
+++ b/build/flags/deps.c
@@ -0,0 +1,8 @@
+// Copyright © Tavian Barnes <tavianator@tavianator.com>
+// SPDX-License-Identifier: 0BSD
+
+/// _CPPFLAGS += -MD -MP
+
+int main(void) {
+	return 0;
+}
-- 
cgit v1.2.3