Visual Studio 包括路径优先级

Visual Studio include path precedence

在花了几个小时试图理解为什么我在 afxtempl.h 中调用 new 时遇到编译错误后,在用尽了通过 google 找到的其他解决方案后,我意识到有一个本地new.h 导致问题(当我说本地时,我的意思是它在构成解决方案的几十个项目之一中)。

这花了一些时间才找到,因为我对代码库只是模糊地熟悉并且没想到会找到 new.h,还因为我不认为这会干扰尖括号

#include <new.h> 

在 afxtempl.h 中。我一直觉得

#include <file.h> 

首先在系统中查找。

查看来自一个有问题的项目的包含路径(除了我的机器上实际上不存在的几个本地路径)是:

$(VC_IncludePath)
$(WindowsSDK_IncludePath)

那么给定 new.h 是(曾经)在不同的项目中,它是如何被拾取的?

此时我应该补充一点,该解决方案刚刚从 VC++ 6 迁移到 VS 2013。

本地new.h顺便说一下没有#define _INC_NEW,还是define/declare新的。名字纯属巧合,与内存分配无关

我很好奇是否有一些我不知道的包含设置,并且不希望以后有同样令人沮丧的几个小时。

谢谢。

首先在每个项目的附加包含目录 (C/C++ - General - Additional Include Directories) 中搜索尖括号包含。这是 documented 行为:

Angle-bracket form

The preprocessor searches for include files in this order:

  • Along the path that's specified by each /I compiler option.

  • When compiling occurs on the command line, along the paths that are specified by the INCLUDE environment variable.

...

For example, the command

CL /ID:\MSVC\INCLUDE MYPROG.C

causes the preprocessor to search the directory D:\MSVC\INCLUDE\ for include files such as STDIO.H.

您的项目目录似乎已添加到附加包含目录列表中。您可以在项目设置的 C/C++ - CommandLine 选项卡中查看传递给编译器的所有命令行选项。

这是 C/C++ 编译器工作的常用方式,例如参见 [​​=18=] 文档:

#include <file>

This variant is used for system header files. It searches for a file named file in a standard list of system directories. You can prepend directories to this list with the -I option (see Invocation).

因此,如果您想保留其他包含目录列表,恐怕无法更改此行为。作为解决方法,您可以将包含文件放在项目根目录的子目录中,并将项目根添加到其他目录列表中,因此您的包含看起来像 #include "project/new.h",但这需要代码重组。