In C/C++, is there a directive similar to #ifndef for typedefs?

Viewed 43714

If I want to define a value only if it is not defined, I do something like this :

#ifndef THING
#define THING OTHER_THING
#endif

What if THING is a typedef'd identifier, and not defined? I would like to do something like this:

#ifntypedef thing_type
typedef uint32_t thing_type
#endif

The issue arose because I wanted to check to see if an external library has already defined the boolean type, but I'd be open to hearing a more general solution.

13 Answers

This is a good question. C and Unix have a history together, and there are a lot of Unix C typedefs not available on a non-POSIX platform such as Windows (shhh Cygwin people). You'll need to decide how to answer this question whenever you're trying to write C that's portable between these systems (shhhhh Cygwin people).

If cross-platform portability is what you need this for, then knowing the platform-specific preprocessor macro for the compilation target is sometimes helpful. E.g. windows has the _WIN32 preprocessor macro defined - it's 1 whenever the compilation target is 32-bit ARM, 64-bit ARM, x86, or x64. But it's presence also informs us that we're on a Windows machine. This means that e.g. ssize_t won't be available (ssize_t, not size_t). So you might want to do something like:

#ifdef _WIN32
typedef long ssize_t;
#endif

By the way, people in this thread have commented about a similar pattern that is formally called a guard. You see it in header files (i.e. interfaces or ".h" files) a lot to prevent multiple inclusion. You'll hear about header guards.

/// @file poop.h

#ifndef POOP_H
#define POOP_H

void* poop(Poop* arg);

#endif

Now I can include the header file in the implementation file poop.c and some other file like main.c, and I know they will always compile successfully and without multiple inclusion, whether they are compiled together or individually, thanks to the header guards.

Salty seadogs write their header guards programmatically or with C++11 function-like macros. If you like books I recommend Jens Gustedt's "Modern C".

There is not such things. It is possible to desactivate this duplicate_typedef compilator error. "typedef name has already been declared (with same type)"

On a another hand, for some standardized typedef definition there is often a preprocessor macro defined like __bool_true_false_are_defined for bool that can be used.

Related