Search code examples
ccompilationmacroscc

How to determine macro value at compilation time in C?


If I have a macro in my C:

#ifdef SIGDET
#if SIGDET == 1
    isSignal = 1;       /*Termination detected by signals*/
#endif
#endif

How can I set the value at compilation time? Is it some parameter to the compiler?


Solution

  • C compilers allow macros to be defined on the command line, usually with the -D command line option:

    This defines the macro SIGDET to the value 1.

    gcc -DSIGDET myprogram.c
    

    You can specify the value this way:

    gcc -DSIGDET=42 myprogram.c
    

    You can even define the macro as empty:

    gcc -DSIGDET=  myprogram.c
    

    Given how your program is written, defining SIGDET as empty would cause a compilation error. Defining SIGDET to 2 would have the same effect as not defining SIGDET at all, this might not be what you expect.

    It might be preferable to consider any numeric definition of SIGDET different than 0 to trigger the conditional code. You could then use these tests:

    #ifdef SIGDET
    #if SIGDET+0
        isSignal = 1;       /*Termination detected by signals*/
    #endif
    #endif
    

    Or this alternative:

    #if defined(SIGDET) && SIGDET+0
        isSignal = 1;       /*Termination detected by signals*/
    #endif