Amit
Amit

Reputation: 187

Scope of #define without a token-string in in C/C++

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

Upvotes: 1

Views: 193

Answers (1)

Yunnosch
Yunnosch

Reputation: 26703

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)

Upvotes: 1

Related Questions