Limit scope of #define labels

后端 未结 9 841
被撕碎了的回忆
被撕碎了的回忆 2020-12-19 05:39

What is the correct strategy to limit the scope of #define labels and avoid unwarranted token collision?

In the following configuration:

相关标签:
9条回答
  • 2020-12-19 06:26

    #defines don't have scope that corresponds to C++ code; you cannot limit it. They are naive textual replacement macros. Imagine asking "how do I limit the scope when I replace text with grep?"

    You should avoid them whenever you possibly can, and favor instead using real C++ typing.

    Proper use of macros will relieve this problem almost by itself via naming convention. If the macro is named like an object, it should be an object (and not a macro). Problem solved. If the macro is named like a function (for example a verb), it should be a function.

    That applies to literal values, variables, expressions, statements... these should all not be macros. And these are the places that can bite you.

    In other cases when you're using like some kind syntax helper, your macro name will almost certainly not fit the naming convention of anything else. So the problem is almost gone. But most importantly, macros that NEED to be macros are going to cause compile errors when the naming clashes.

    0 讨论(0)
  • 2020-12-19 06:33

    C is a structured programming language. It has its limitations. That is the very reason why object oriented systems came in 1st place. In C there seems to be no other way, then to understand what your header files's variables start with _VARIABLE notation, so that there are less chances of it getting over written.

    in header file 
    _ZERO 0
    
    in regular file
    
    ZERO 0
    
    0 讨论(0)
  • 2020-12-19 06:34
    1. I think the correct strategy would be to place #define labels - in only the implementation, ie. c, files
    2. Further all #define could be put separately in yet another file- say: Utility_2_Def.h
      (Quite like Microsoft's WinError.h:Error code definitions for the Win32 api functions)

      Overheads:

      1. an extra file
      2. an extra #include statement

      Gains:

      1. Abstraction: ZERO is: 0, '0' or "Zero" as to where you use it
      2. One standard place to change all static parameters of the whole module

    Utility_2.h

    BOOL Utility_2();
    

    Utility_2_Def.h

    # define ZERO '0'
    # define ONE  '1'
    

    Utility_2.c

    # include "Utility_2.h"
    # include "Utility_2_Def.h"
    
    BOOL Utility_2()
    {
        ...
    }
    
    0 讨论(0)
提交回复
热议问题