1

I have the following files:

Main.c

#include "Header.h"

#define SECRET_NUMBER_ENABLED

int main()
{
    printf("Secret number = %d\n", SECRET_NUMBER);
    return 0;
}

Header.h

#ifdef SECRET_NUMBER_ENABLED
    #define SECRET_NUMBER 111
#else
    #define SECRET_NUMBER 222
#endif

The print result is: 222

To my understanding, the Pre-Processor should scan Main.c and replace every SECRET_NUMBER with its defined number from Header.h,

And because SECRET_NUMBER_ENABLED is defined in Main.c, the Pre-processor should take the 111 definition instead of the 222.

Apparently I'm wrong, but I don't know why, and don't know how to set it correctly so only C files which have #define SECRET_NUMBER_ENABLED will use SECRET_NUMBER 111

Amit
  • 165
  • 1
  • 9
  • did you try to put `#define SECRET_NUMBER_ENABLED` before the `#include` ? – CrApHeR Apr 08 '15 at 11:44
  • Yes, same results, altough I am getting compilation warning: warning C4603: 'SECRET_NUMBER_ENABLED' : macro is not defined or definition is different after precompiled header use – Amit Apr 08 '15 at 11:54
  • My full code had the following includes: #include "stdafx.h" #include "Header.h" when I put the define between them it works, when I put the define before the 2 includes i Get the warning above, and it doesn't work, can you explain why? – Amit Apr 08 '15 at 15:20
  • I have an stupid comment, but how knows... Did you check assigning a different name to the define `SECRET_NUMBER_ENABLED`? Maybe there is a define with that name in the stdafx.h or its dependences – CrApHeR Apr 09 '15 at 00:03
  • Yes, I checked a different name, still doesn't work. – Amit Apr 12 '15 at 06:32
  • Including stdafx.h messes with already defined macros. Only macros defined afterwards are safe. http://stackoverflow.com/questions/16040689/why-stdfax-h-should-be-the-first-include-on-mfc-applications – Yunnosch Apr 11 '17 at 17:30

1 Answers1

1

Anything before including "stdafx.h" is assumed to have already been defined.
See Why stdfax.h should be the first include on MFC applications?

So any earlier definition gets lost.

That is why you need to define your macros

  • after including stdafx.h
    (because otherwise they get ignored)
  • before including your own header
    (because otherwise they wont have an effect on your header,
    the #ifdef inside your header is evaluated before the definition in main.c is seen)
Community
  • 1
  • 1
Yunnosch
  • 26,130
  • 9
  • 42
  • 54