Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#ifdef not working as expected with precompiled headers

Tags:

c++

macros

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.

like image 726
someone_ smiley Avatar asked Jul 31 '13 04:07

someone_ smiley


1 Answers

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

}
like image 52
Öö Tiib Avatar answered Nov 01 '22 16:11

Öö Tiib