Defer Macro Warning: This is experimental, relies on GCC-specific extensions (__attribute__((cleanup)) and nested functions), and is not portable C. It’s just for fun and exploration. While working on my operating system project, RetrOS-32, I ran into some of GCC’s less common function attributes. One that stood out to me was the cleanup attribute, which lets you tie a function to a variable. When the variable goes out of scope, that function is called automatically. At first this sounded like an easy way to manage resources in C, a language where you normally have to handle everything by hand.Here’s an example:/* The function must take one parameter, * a pointer to a type compatible with the variable. * The return value of the function (if any) is ignored. */ void free_ptr(void* ptr) { free(*(void**)ptr); } int example(){ __attribute(cleanup(free_ptr)) char* ptr = malloc(32); return 0; }This works, but it isn’t exactly safe. If malloc fails and returns NULL, the cleanup function will still be called, and there’s no simple way to add a guard inside free_ptr. Because of issues like that, I didn’t really use the feature at first.That changed when I came across a blog post by Jens Gustedt, where he showed how the cleanup attribute could be combined with another GCC feature, nested functions, to build something more practical: a defer mechanism, similar to what languages like Go provide.Nested functionsNested functions are not part of standard C, but GCC supports them. They allow you to declare a function inside another function, and the inner one has access to the variables of the outer scope.int example() { int a = 1; void set(){ a = 2; } set(); return a; }This ability to reach into the parent scope is what makes a defer macro possible. Jens’ approach uses cleanup to ensure the nested function is executed when leaving the scope, giving you a way to run code automatically at the end of a block.Jens' defer macro is defined below:#define __DEFER__(F, V) \ auto void F(int...
First seen: 2025-10-01 07:41
Last seen: 2025-10-01 15:43