Defining macro on the command-line vs in the source

N

Noob

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.
 
X

Xavier Roche

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).

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

(...)
-D name
Predefine name as a macro, with definition 1.
So I can't just write
#if FOO1 && FOO2 && !FOO3 && (FOO4 || !FOO5)

If you insist on allowing -Dname=0, you may use:

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

otherwise, defined(FOO1) would probably be sufficient.
 
J

James Kuyper

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

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
 
P

Philip Lantz

James said:
This is indeed tool dependent...

Strictly speaking, yes, but in over 30 years of C programming I've never
seen a compiler that did it differently.
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top