Precedence of -D MACRO and #define MACRO

后端 未结 5 622
情歌与酒
情歌与酒 2021-01-11 14:24

If I have a C file foo.c and while I have given -DMACRO=1 as command line option for compilation. However, if within the header file also I hav

相关标签:
5条回答
  • 2021-01-11 15:12

    The command line options apply ahead of any line read from a file. The file contents apply in the order written. In general, you will get at least a warning if any macro is redefined, regardless of whether the command line is involved. The warning may be silenced if the redefinition doesn't matter, perhaps because both definitions are identical.

    The right way to answer a question like this is to build a small test case and try it. For example, in q3965956.c put the following:

    #define AAA 2
    AAA
    

    and run it through the C preprocessor, perhaps with gcc -E:

    C:>gcc -DAAA=42 -E q3965956.c
    # 1 "q3965956.c"
    # 1 ""
    # 1 ""
    # 1 "q3965956.c"
    q3965956.c:1:1: warning: "AAA" redefined
    :1:1: warning: this is the location of the previous definition
    
    2
    
    C:>
    

    You can see from the output that the macro expanded to the value given by the #define in the file. Furthermore, you can see from the sequence of # directives that built-in definitions and the command line were both processed before any content of line 1 of q3965956.c.

    0 讨论(0)
  • 2021-01-11 15:18

    I'm making an assumption of what you're doing, but if you'd like to supply from the command-line a non-default value for that macro, try this for the macro definition:

    #ifndef MACRO
    #define MACRO 2
    #endif
    

    That way if the MACRO has already been defined (via command-line parameter) it will neither be redefined nor result in an error.

    0 讨论(0)
  • 2021-01-11 15:22

    manual says: first all -D and -U are evaluated in order and then all -includes (under section -D)

    best way: try it out.

    0 讨论(0)
  • 2021-01-11 15:28

    You'll get an error for macro redefinition. Obviously -D gets defined first (before the source file is parsed rather than after) or it would have no use. The #define is then a redefinition.

    0 讨论(0)
  • 2021-01-11 15:29

    Defines are stored in order the compiler sees them, and when the compiler encounters a new macro with the same name, it overwrites the previous macro with the new one (at least this is the case in gcc). GCC will also give you a warning when this happens.

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