Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How did C99 do type generic macros without _Generic (C11)?

While looking at the sqrt function for tgmath.h,
I see that there is a type-generic macro for C99.

I know how I would implement it with Generic selection,
but _Generic did not exist until C11.

We have legacy projects in C89, and C99.
I would like to implement type generic functionality in a similar fashion if possible.

How does one write type generic macros in C without Generic selection?

like image 917
Trevor Hickey Avatar asked Dec 14 '25 20:12

Trevor Hickey


1 Answers

How did C99 do type generic macros without _Generic (C11)?

Non-portably.

There is no general way to write a type-generic macro in pre-C11 C.

If you look at the tgmath.h header provided as part of glibc, for example, it doesn't use _Generic (since it needs to work with compilers that don't support _Generic). Instead, it uses a number of gcc-specific features such as __builtin_classify_type wrapped in some remarkable macros. A comment near the top of the file says:

/* This is ugly but unless gcc gets appropriate builtins we have to do        
   something like this.  Don't ask how it works.  */

Some of the macro definitions compare sizeof (Val) (where Val is the macro argument) vs. sizeof (double). This could fail if float, double, and long double do not all have distinct sizes.

And the whole thing is wrapped in:

#if __GNUC_PREREQ (2, 7)
/* a lot of ugly macro definitions */
#else
# error "Unsupported compiler; you cannot use <tgmath.h>"
#endif

You could probably throw something together using sizeof, but it would be ugly.

Is there any chance you could compile your legacy code with a compiler that supports C11, or at least the _Generic feature?

like image 151
Keith Thompson Avatar answered Dec 17 '25 21:12

Keith Thompson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!