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

Solution 1:

There is no such thing in the language, nor is it needed. Within a single project you should not have the same typedef alias referring to different types ever, as that is a violation of the ODR, and if you are going to create the same alias for the same type then just do it. The language allows you to perform the same typedef as many times as you wish and will usually catch that particular ODR (within the same translation unit):

typedef int myint;
typedef int myint;       // OK: myint is still an alias to int
//typedef double myint;  // Error: myint already defined as alias to int

If what you are intending to do is implementing a piece of functionality for different types by using a typedef to determine which to use, then you should be looking at templates rather than typedefs.

Solution 2:

C++ does not provide any mechanism for code to test presence of typedef, the best you can have is something like this:

#ifndef THING_TYPE_DEFINED
#define THING_TYPE_DEFINED
typedef uint32_t thing_type 
#endif

EDIT:
As @David, is correct in his comment, this answers the how? part but importantly misses the why? It can be done in the way above, If you want to do it et all, but important it you probably don't need to do it anyways, @David's answer & comment explains the details, and I think that answers the question correctly.

Solution 3:

No there is no such facility in C++ at preprocessing stage. At the max can do is

#ifndef thing_type
#define thing_type uint32_t 
#endif

Though this is not a good coding practice and I don't suggest it.

Solution 4:

Preprocessor directives (like #define) are crude text replacement tools, which know nothing about the programming language, so they can't act on any language-level definitions.

There are two approaches to making sure a type is only defined once:

  • Structure the code so that each definition has its place, and there's no need for multiple definitions
  • #define a preprocessor macro alongside the type, and use #ifndef to check for the macro definition before defining the type.

The first option will generally lead to more maintainable code. The second could cause subtle bugs, if you accidentally end up with different definitions of the type within one program.

Solution 5:

As other have already said, there are no such thing, but if you try to create an alias to different type, you'll get a compilation error :

typedef int myInt;
typedef int myInt;    // ok, same alias
typedef float myInt;  // error

However, there is a thing called ctag for finding where a typedef is defined.