aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorkartofen <mladenovnasko0@gmail.com>2023-05-30 23:14:30 +0300
committerkartofen <mladenovnasko0@gmail.com>2023-05-30 23:14:30 +0300
commitd53ac76f78762b7bfd395576fd2ba5ed39f515c1 (patch)
tree105ab8b6a57a0b1296fe3f0a8dab97faa40d204f
parent93b71ee9b3cd95ed346370e37ef1fdcb3c01520f (diff)
templates in cHEADmaster
-rw-r--r--Makefile9
-rw-r--r--c-templates.c34
2 files changed, 41 insertions, 2 deletions
diff --git a/Makefile b/Makefile
index fc927b7..7a78977 100644
--- a/Makefile
+++ b/Makefile
@@ -3,7 +3,7 @@ CC := gcc
CFLAGS := -Wall -Wextra -Wpedantic
BIND := bin
-CSRCS = $(shell find . -type f -name '*.c')
+CSRCS = $(shell find * -type f -name '*.c')
.PHONY: all clean
@@ -12,6 +12,11 @@ all: $(CSRCS:%.c=$(BIND)/%)
clean:
rm -rf $(BIND)
+$(BIND)/c-templates: c-templates.c
+ mkdir -p $(dir $@)
+ gcc -E -CC $^ | gcc -E -CC -DDEFINE=\#define -xc - | gcc $(CFLAGS) --std=gnu99 -o $@ -xc -
+
$(BIND)/%: %.c
- mkdir -p $(dir $@)p
+ @echo $@
+ mkdir -p $(dir $@)
$(CC) $(CFLAGS) $^ -o $@
diff --git a/c-templates.c b/c-templates.c
new file mode 100644
index 0000000..d9f9846
--- /dev/null
+++ b/c-templates.c
@@ -0,0 +1,34 @@
+#include <stdio.h>
+
+// Build using:
+// gcc -E -CC c-templates.c | gcc -E -CC -DDEFINE=\#define -xc - | gcc --std=gnu99 -xc -
+
+#define TEMPLATE_VA_ARGS __VA_ARGS__
+#define template(name, ...) /*
+*/ DEFINE name(types, ...) __TEMPLATE_##name types f(TEMPLATE_VA_ARGS); }) /*
+*/ DEFINE __TEMPLATE_##name(__VA_ARGS__) ({
+
+// template syntax:
+// declare: template(name, ... types) return_t f(... args) { ... body }
+// call: name((... types), ... args)
+
+template(print_hex, T) void f(T c) /*
+*/{ /*
+*/ printf("%x\n", c); /*
+*/}
+
+template(max, T) T f(T a, T b) /*
+*/{ /*
+*/ return (a > b) ? a : b; /*
+*/}
+
+int main(void)
+{
+ print_hex((int), 16);
+ print_hex((int), '\n');
+
+ printf("%d\n", max((int), 5, 10));
+ printf("%f\n", max((float), 362.38098f, 7.4323f));
+ printf("%ld\n", max((long), 409343432, 430483249));
+ return 0;
+}