c++ - 在预编译单元中定义宏条件语句是否明智?

标签 c++ visual-c++ msbuild precompile precompiled-headers

******* 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 ....../
**************************

当我编译 dummy.cpp 时,Visual C++ 编译器弹出以下编译器错误:

错误 C2856:#pragma hdrstop 不能在 #if block 内

为了防止上述错误,我将宏条件语句移植到stdafx.h预编译中,如下所示:

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

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

这是避免上述预编译单元编译错误的好方法吗?

最佳答案

这种方法行不通。在编译过程中忽略预编译 header 包含之前的所有内容,因此 #if defined (_MSC_VER) in dummy.cpp 将被丢弃。

更好的方法是删除所有#include "stdafx.h" 并通过编译选项Forced Include File 包含预编译 header :

/FI"stdafx.h"

关于c++ - 在预编译单元中定义宏条件语句是否明智?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48986712/

相关文章:

c++ - 是否可以推迟过载决议?

c++ - map int<-->int, 1 :N, 已知边界

sockets - 如何使用 Win32 TransmitFile() 传输大于 2,147,483,646 字节 (~2 GiB) 的文件?

Jenkins MSBuild 失败,错误 NETSDK1064 : Package Microsoft. CodeAnalysis.Analyzers,未找到版本 2.9.3

visual-studio-2015 - 我在哪里可以找到 Visual Studio 2015 中的 Microsoft.TeamFoundation.Build.Client?

msbuild - CSC 错误 CS0006 : Metadata file 'SonarAnalyzer.dll' could not be found

c++ - 在 C++ 中转发声明枚举

visual-c++ - 如果字符串是使用 Visual Studion Windows 窗体从 Visual C++ 中的文本框中获取的,则字符串到整数类型的转换

C++:如何简化线程锁?

c++ - C++ 中是否有 'override' 说明符的反转?