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

后端 未结 11 2215
太阳男子
太阳男子 2020-12-15 16:03

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

相关标签:
11条回答
  • 2020-12-15 16:25

    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.

    0 讨论(0)
  • 2020-12-15 16:28

    No there is nothing like what you wanted. I have had your same problem with libraries that include their owntypedefs for things like bool. It gets to be a problem when they just don't care about what you use for bool or if any other libs might be doing the same thing!!

    So here's what I do. I edit the header file for the libs that do such things and find the typedef bool and add some code like this:

    #ifdef USE_LIBNAME_BOOL
    typedef unsigned char bool; // This is the lib's bool implementation
    #else
    #include <stdbool.h>
    #endif
    

    Notice that I included if I didn't want to use the libs' own bool typdef. This means that you need C99 support or later.

    0 讨论(0)
  • 2020-12-15 16:29

    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.

    0 讨论(0)
  • 2020-12-15 16:29

    As mentioned before this is not included in the C++ standard, but you might be able to use autotools to get the same functionality.

    You could use the ac_cxx_bool macro to make sure bool is defined (or different routines for different datatypes).

    0 讨论(0)
  • 2020-12-15 16:32

    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.

    0 讨论(0)
提交回复
热议问题