C++ – #ifdef not working as expected with precompiled headers

cmacros

I have part of code like below:

#define FEATURE_A 1

void function()
{
// some code

#ifdef FEATURE_A
    // code to be executed when this feature is defined
#endif

// some code

}

The program does not execute code inside #ifdef#endif. But when I change #ifdef to #ifndef and remove #define macro, the code get executed. The code below work as expected.

//#define FEATURE_A 1

void function()
{
// some code

#ifndef FEATURE_A
    // code to be executed when this feature is defined
#endif

// some code

}

Can anyone explain why in the first case code inside #ifdef#endif not executed and in second case it work? Can anyone tell me what setting might be wrong?

Not sure if this matter, I'm using visual studio 2010.

Thanks in advance

UPDATE :
When I clean and re-run, the second one also not working. its only show in editor as code that enabled.

When I define macro in project->property->Configuration Properties-> c/c++ -> Preprocessor , both of them working fine.

Best Answer

It is likely because of how Microsoft implements precompiled headers. You actually have

#define FEATURE_A 1
#include "stdafx.h" // <- all code even ascii art before that line is ignored.

void function()
{
// some code

#ifdef FEATURE_A
    // code to be executed when this feature is defined
#endif

// some code

}

Move it after precompiled header and all works:

#include "stdafx.h" // <- all code even ascii art before that line is ignored.
#define FEATURE_A 1

void function()
{
// some code

#ifdef FEATURE_A
    // code to be executed when this feature is defined
#endif

// some code

}
Related Topic