__attribute__ ((cleanup)), or how I came to love C again

If your project is written in C, and you don’t mind having a hard dependency on GCC (i.e. you don’t care about building with MSVC++), this GNU C extension does amazing things for your code.

There are other GNU C extensions that are simultaneously useless and crazy, but __attribute__ ((cleanup)) makes up for everything else. For reference, here’s a discussion about using it in GNOME.


8 comments

  1. pretty cool indeed.

    I was also planning to propose a wrapper for __attribute__((nonnull, argidx, …)) to get compiler warnings when passing NULL, instead of getting run-time warnings only through g_return_if_fail()/g_return_val_if_fail().

  2. Automatically running a cleanup function when a variable goes out of scope? That’s really neat. I seem to recall some Danish guy invented a C extension to do that a while ago, along with a few other useful things. He called it “C with Classes” or something. Does anyone know what happened to it?

    • Yeah, I know what you’re talking about… I believe it still has a modest cult following, and the latest version has type inferencing, garbage collection, even macros (after a fashion)… what’s it called? It was on the tip of my tongue… Chainsaw?

    • Indeed, this feature is one of the best parts of C++, but there’s a *whole lot* of other stuff that comes with C++, not all of it good…

      Anyways, the model where the best ideas filter back down into C is nice.

  3. +1 for Tristan. “cleanup” is a hack to provide destructors in C, and the implementation uses the same code as GCC uses for that Danish guy’s C extension. With a little more effort, you can modify this hack to work either with the GCC cleanup extension, or with any C++ compiler.

  4. What I find ironic is that you linked to nested functions as “useless and crazy”… but the very example of cleanup that you linked to in wikipedia uses a nested function in the #define to create a local nested destructor!

    Nevermind, thank you a lot for the information! Although I agree with Joe that cleanup is a hack, I am sure to use it more and more in my own code!

    Very interesting!

  5. Very impressive. I wonder how much work it would take to generalize from this to Go’s “defer” mechanism?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s