2

I have the following code in a global header, so I can make decisions at compile time:

enum {
    MyStyleA,
    MyStyleB,
    MyStyleC
};

#define STYLE MyStyleB

In various source files, I include this header and do something like this:

#if STYLE == MyStyleC
    doSomething();
#endif

Problem is, doSomething() definitely gets executed even though I defined STYLE to MyStyleB in the header!

Any idea what's going wrong here?

(I admit I am no C preprocessor expert.)

4

2 に答える 2

2

I don't have a copy of the C standards on my bedside table, so I could be wrong, but:

The preprocessor has no idea what MyStyleC is - that doesn't get a value until it hits the compiler.

Compilers normally have an option (used to be -e ?) to output the results of the preprocessor phase (as text) - I'd look at that and see what your #if looks like after the preprocessor has gone over it.

于 2012-12-16T23:31:17.063 に答える
1

The preprocessor has no knowledge about the semantics of your code, it only does literal macro substitution so it can work with constant expressions only. How about writing

if (STYLE == MyStyleC) {
    doSomething();
}

instead?

于 2012-12-16T23:29:26.917 に答える