Thomas Carter <T.******@nanobots.com> writes:
On Thu, 06 Apr 2006 18:53:58 +0000, Thomas Carter wrote:
Imagine that there is some include file f.h that contains the following
line:
typedef unsigned int ui32 ;
My question is: If I have a C source file F.c that includes f.h, is it
possible for the preprocessor to detect that ui32 already exists, when
preprocessing F.c? The idea is that F.c will typedef ui32 as above if and
only if such typedef is not already in some include file used by F.c.
Thanks everybody for your suggestions. I forgot to point out that, in
general, one is not allowed to modify f.h. I guess that with such
restriction, what I want to do in general just can't be done.
There are ways to do it if you're wiling to go beyond the scope of
what the compiler alone can do for you.
For example, you can create a small test program that attempts to use
ui32:
#include "f.h"
#include <stdio.h>
int main(void)
{
ui32 dummy;
printf("ok\n");
return 0;
}
Attempt to compile and execute the program. If it prints "ok", the
typedef exists; otherwise, it doesn't. Use this result to generate,
say, another header file to be included by F.c (is that really an
uppercase "F"?). The generated header file might just include a
series of #define directives. Depending on your environment, a
reasonably simple shell script, batch file, or equivalent should do
the job.
Your F.c might then contain something like this:
#include "f.h"
#include "config.h"
....
#ifndef UI32_DEFINED
typedef unsigned int ui32;
#endif
....
If you're doing this kind of thing a lot, you might consider using a
tool like GNU autoconf (which is off-topic here, but easy to google).
You also need to be aware of what assumptions you're making. Type
unsigned int isn't necessarily 32 bits; it can be 16, 64, or even 47,
and even if it's 32 bits, some of them could be padding bits. There
might not even be a 32-bit integer type (though there will always be
some integer type that's *at least* 32 bits).
Ideally, you should use the <stdint.h> header, which defines typedefs
such as uint32_t, along with macros that let you determine whether
they're defined. The <stdint.h> header is new in C99, but it's not
difficult to implement most of it in C90; see Doug Gwyn's q8,
<http://www.lysator.liu.se/c/q8/index.html>.
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.