Portable equivalent to gcc's __attribute__(cleanup)

There's no portable way in C.

Fortunately it's a standard feature of C++ with destructors.

Edit:

MSVC appears to have __try and __finally keywords which can be used for this purpose as well. This is different than the C++ exception handling and I think it's available in C.

I think you'll find that cleanup and try/finally aren't widely used specifically because of the implicit support in C++, which is "close enough" to C that people interested in the behavior can switch their code to C++ with ease.


The first half of your question is the portable way to do it.


__attribute__(cleanup) is not gcc-specific, it is also supported by clang and icc, making msvc the only major compiler that doesn't support it (and that one is pretty useless for modern C development anyway).

So even if it is not in the ISO standard, it can be considered portable for most practical purposes.