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

后端 未结 11 2246
太阳男子
太阳男子 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: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.

提交回复
热议问题