Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

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.

like image 601
Zach Rattner Avatar asked Jul 21 '11 07:07

Zach Rattner


People also ask

What is #define directive in C?

The #define creates a macro, which is the association of an identifier or parameterized identifier with a token string. After the macro is defined, the compiler can substitute the token string for each occurrence of the identifier in the source file.

Can we use Elif in C?

In the C Programming Language, the #elif provides an alternate action when used with the #if, #ifdef, or #ifndef directives.

What does #ifdef do in C?

The #ifdef is one of the widely used directives in C. It allows conditional compilations. During the compilation process, the preprocessor is supposed to determine if any provided macros exist before we include any subsequent code.

Why Ifndef is used in C?

In the C Programming Language, the #ifndef directive allows for conditional compilation. The preprocessor determines if the provided macro does not exist before including the subsequent code in the compilation process.


1 Answers

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.

like image 191
David Rodríguez - dribeas Avatar answered Sep 25 '22 17:09

David Rodríguez - dribeas