Defining macro on the command-line vs in the source

Discussion in 'C Programming' started by Noob, Aug 29, 2013.

  1. Noob

    Noob Guest

    Hello,

    I suppose this topic is tool-specific, but it seems to me
    many tools have adopted the same behavior.

    I had always been under the (mistaken) impression that defining
    a macro on the command line (with -D) was equivalent to defining
    it in my source file (with #define).

    In other words, that

    cc -DFOO bar.c

    was equivalent to having

    #define FOO

    as the first line of bar.c

    but it appears I was wrong...

    -DFOO seems, in fact, to be equivalent to
    #define FOO 1
    (and also to -DFOO=1 but I digress)

    So I can't just write
    #if FOO1 && FOO2 && !FOO3 && (FOO4 || !FOO5)

    if FOOi could be either defined on the command line
    or as a simple #define in the source file, right?

    If I want to use the syntax without defined(),
    I have to actually define the macro to 1.

    I think it is guaranteed that an undefined macro
    will have value 0 in a #if expression, right?

    Regards.
     
    Noob, Aug 29, 2013
    #1
    1. Advertisements

  2. Noob

    Xavier Roche Guest

    Indeed, no - at least not with GCC or clang:

    (...)
    -D name
    Predefine name as a macro, with definition 1.
    If you insist on allowing -Dname=0, you may use:

    #if ( defined(FOO1) && FOO1 && defined(FOO2) && FOO2 ... )

    otherwise, defined(FOO1) would probably be sufficient.
     
    Xavier Roche, Aug 29, 2013
    #2
    1. Advertisements

  3. Noob

    James Kuyper Guest

    This is indeed tool dependent, and I'm surprised to find that gcc works
    this way - that's not how I remember it working. However,

    -DFOO=

    will do the equivalent of

    #define FOO
     
    James Kuyper, Aug 29, 2013
    #3
  4. Noob

    Philip Lantz Guest

    Strictly speaking, yes, but in over 30 years of C programming I've never
    seen a compiler that did it differently.
     
    Philip Lantz, Sep 1, 2013
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.