How does the magic work? Starting from the last line:
__attribute__((cleanup(…)))
— an extension to the C language, provided by GCC and Clang. When a variable is tagged with this attribute, the specified function is invoked when the variable leaves scope.void (^…)(void) = ^{ … }
— C Blocks, an extension to the C language, provided by Clang or GCC with Apple’s Blocks patch. Allows you to define inline, anonymous functions. In this case, I’m taking the block that’s expected to appear after the defer macro and assigning it to a local variable.a##b
— merge two strings into a single token. By combiningdefer_scopevar_
with the__COUNTER__
, I get a unique variable name.void defer_cleanup(void (^*b)(void)) { (*b)(); }
— a C function that takes a block as its parameter. I pass this function to__attribute__((cleanup(…)))
, and it gets invoked when the variable (defined in step #2) leaves scope. When the function is invoked, it just calls the block that was passed to it. (This indirection is necessary since__attribute__((cleanup(…)))
doesn’t directly support C Blocks.)