Search code examples
c++visual-c++msbuildprecompileprecompiled-headers

Is it wise to define macro conditional statement within Precompilation unit?


******* stdafx.h ********
#pragma once

#include "targetver.h"
#define WIN32_LEAN_AND_MEAN             
// Windows Header Files:
#include <windows.h>

**************************

******* dummy.cpp ********
    #if defined (_MSC_VER)
    #include "stdafx.h"
    #endif
    /........ content ....../
**************************

when I compiled dummy.cpp ,following compiler error pops up with Visual C++ compiler:

error C2856: #pragma hdrstop cannot be inside an #if block

In order to prevent above error I port macro conditional statement in to stdafx.h pre-coompilation as below:

    ******* stdafx.h ********
    #pragma once

    #if defined (_MSC_VER)
     #include "targetver.h"
     #define WIN32_LEAN_AND_MEAN             
     // Windows Header Files:
     #include <windows.h>
    #endif 
    **************************

Is this a good approach to avoid compilation error on above pre-compilation unit?


Solution

  • This approach won't work. Everything before precompiled header inclusion is ignored during compilation so #if defined (_MSC_VER) in dummy.cpp will be thrown away.

    The better approach would be delete all the #include "stdafx.h" and include precompiled header through compilation option Forced Include File:

    /FI"stdafx.h"