You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: _posts/2025-11-30-comptime-c-functions.md
+76-21Lines changed: 76 additions & 21 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -9,21 +9,21 @@ Compile-time function execution is great, but what if:
9
9
2. You don't want to use evil C macros, which are debugging nightmares.
10
10
3. You want generic data structures that work for all types.
11
11
12
-
The below data structure showcase programs get optimized away at compile time by Clang and GCC, such that only the `printf()` at the end of `main()` is left:
12
+
The below data structure showcase programs get optimized away at compile time by Clang and GCC:
13
13
```nasm
14
-
main:
15
-
push rax
16
-
lea rdi, [rip + .Lstr]
17
-
call puts@PLT ; printf() got translated to the faster puts()
18
-
xor eax, eax
19
-
pop rcx
20
-
ret
14
+
fn_version:
15
+
ret
16
+
17
+
macro_version:
18
+
ret
21
19
```
22
20
23
21
Here is how it is achieved in C:
24
22
-`static inline` allows inlining across compilation boundaries.
25
23
-`__attribute__((always_inline))`*strongly* urges compilers to inline functions.
26
24
-`__builtin_unreachable()` is used to teach the optimizer which assumptions it can make about input arguments.
25
+
- Passing `-O3` to the compiler tells it to optimize the code very hard.
26
+
- Passing `-march=native` to the compiler tells it to make optimizations based on your specific CPU.
27
27
- Constant buffer addresses + sizes let the optimizer trace through `memcpy()` calls.
28
28
- All operations become statically analyzable, reducing to constants.
29
29
-`assert()` calls get eliminated when conditions are provably true.
@@ -36,9 +36,7 @@ The only legitimate use-case I can think of for this technique is generating loo
36
36
37
37
# Generic Stack
38
38
39
-
Clang and GCC require `-O1`.
40
-
41
-
Copy of the code on [Compiler Explorer](https://godbolt.org/z/Y86szvfeG):
39
+
Copy of the code on [Compiler Explorer](https://godbolt.org/z/h9narbMG8):
42
40
43
41
```c
44
42
#include<assert.h>
@@ -47,6 +45,7 @@ Copy of the code on [Compiler Explorer](https://godbolt.org/z/Y86szvfeG):
0 commit comments