Detect usage of macro? (C, preprocessor)
Posted: Fri Aug 28, 2009 8:08 am
Cross-posting from StackOverflow.com, because I hold the programming skills assembled here in high regard:
This is very specific, and a bit difficult to explain, and quite likely impossible, but here goes. Perhaps some C cracks out there have an idea...
I want to implement <errno.h>. (My hobby project is implementing a Standard C library.)
The naive way to go about it is:
This works. But it has one disadvantage: If a math library function is called, it always has to query the FPU status after execution to set errno as appropriate. This stalls the FPU in math-heavy applications.Code: Select all
// in <errno.h> extern int errno; // in some .c file int errno = 0;
The C standard endorses lazy evaluation of errno by making it a macro instead:
This way, errno is only "set" when its value is actually requested:Code: Select all
int * __errno(); #define errno *__errno()
Given some logic in the rest of the library, the FPU status needs only be queried if the last library function called was actually one using the FPU, and the value of errno is actually requested.Code: Select all
// "__errno()" returns the location of the current errno value, // the "errno" macro turns it into a value. x = errno;
So far, everything is fine. But it's the other way around that is giving me headaches:
The value of errno is not requested at all. But __errno() does not know that, and will query the FPU status if the last library function called was using the FPU.Code: Select all
errno = 0;
Right now I don't see a way to avoid that (i.e., have the errno macro or the __errno() function somehow work differently depending on whether they are used to the left or the right of the assignment operator), and am almost content to accept this.
But perhaps any of you OSDev'ers has a brilliant idea?