This Time Self-Hosted
dark mode light mode Search

Macros versus static inline

In my post about glib byte swapping functions I pointed out the inconsistent behaviour of glib’s macros for byteswapping, when it comes down to argument evaluation. If you look at the comments in that post, you can see that Paul points out that a very useful way to do the same thing without the problem of inconsistencies is simply to use inline functions rather than macro. I agree with him that it’s a much more useful thing to do.

Indeed, static inline functions, when the compiler supports them properly (which means, not with Sun Studio compiler), are quite better than macros: their arguments are evaluated just once, always, consistently, they have their own scope for variable names so that you can’t introduce a mystic error in your code by using the same name as a local variable in a macro, they leave the compiler free to decide what the best course of action is for them, for instance, in a loop, and so on. Additionally, they make debug a little easier than macros; when I fixed my problem with scanelf I had a segmentation fault inside a macro call for a 17 lines macro. Not exactly the nicest thing to debug (and actually made me quite wary of scanelf, I start not to like it too much, considered that complexity of the code), as you might guess.

So at the end I decided to go for it, and I submitted a patch to glib that replaces all the byteswapping macros with static inline functions; the code emitted is the same with GCC 4.3 but they are in my opinion more readable and they have more chances to work with non-GNU compilers (the previous implementation for them used the __extension__ keyword that as you might guess is a GNU extension, while static inline is a standard C99 feature).

Hopefully the patch will be merged soon, and at least the newer versions of glib will have a behaviour much more consistent with other libraries too. Now, if I can get to actually benchmark base64 encoding and decoding, and digesting through MD5 and SHA1, comparing glib with libavutil, I’d know what to look at for improvement.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.