Tech News
← Back to articles

Defer available in gcc and clang

read original related products more articles

About a year ago I posted about defer and that it would be available for everyone using gcc and/or clang soon. So it is probably time for an update.

Two things have happened in the mean time:

A technical specification (TS 25755) edited by JeanHeyd Meneide is now complete and moves through ISO’s complicated publication procedures.

Both gcc and clang communities have worked on integrating this feature into their C implementations.

I have not yet got my hands on the gcc implementation (but this is also less urgent, see below), but I have been able to use clang’s which is available starting with clang-22.

I think that with this in mind everybody developing in C could and should now seriously consider switching to defer for their cleanup handling:

no more resource leakage or blocked mutexes on rarely used code paths,

no more spaghetti code just to cover all possibilities for preliminary exits from functions.

I am not sure if the compiler people are also planning back ports of these features, but with some simple work around and slightly reduced grammar for the defer feature this works for me from gcc-9 onward and for clang-22 onward:

#if __has_include() # include # if defined(__clang__) # if __is_identifier(_Defer) # error "clang may need the option -fdefer-ts for the _Defer feature" # endif # endif #elif __GNUC__ > 8 # define defer _Defer # define _Defer _Defer_A(__COUNTER__) # define _Defer_A(N) _Defer_B(N) # define _Defer_B(N) _Defer_C(_Defer_func_ ## N, _Defer_var_ ## N) # define _Defer_C(F, V) \ auto void F(int*); \ __attribute__((__cleanup__(F), __deprecated__, __unused__)) \ int V; \ __attribute__((__always_inline__, __deprecated__, __unused__)) \ inline auto void F(__attribute__((__unused__)) int*V) #else # error "The _Defer feature seems not available" #endif

... continue reading