我如何将没有 运行 的 Psapi.h 包含在乘法包含错误中?

How would I include Psapi.h without running into a multiply included error?

目前 运行 遇到一个问题,其中 Winsock.h 已经包含在我项目其他地方的 header 文件中...

Header不直接包含:

# if defined(_WINSOCKAPI_) && !defined(_WINSOCK2API_)
# error WinSock.h has already been included
# endif // defined(_WINSOCKAPI_) && !defined(_WINSOCK2API_)

所以当我尝试构建时,我得到一个错误 "C1189 Winsock.h has already been included"(来自上面代码段中定义的错误消息)。

但是,我需要能够使用parts of the PSAPI来获取关于当前进程的内存使用信息。我试图在我的其他文件中包含...

我的 .cpp 文件:

#include <Windows.h>
#include <Psapi.h>

...

SIZE_T getMemoryInfo() {    // The function that needs the includes

    PROCESS_MEMORY_COUNTERS pmc;
    SIZE_T memoryUsed;

    GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc));
    memoryUsed = pmc.WorkingSetSize;

    return memoryUsed;

}

研究之后,我尝试使用 WIN32_LEAN_AND_MEAN 来尝试摆脱 Winsock.h 包含,这有效,但是现在当我尝试使用 PROCESS_MEMORY COUNTERS 时,我得到一个未定义的符号错误...

"LNK2019 unresolved external symbol GetProcessMemoryInfo referenced in function..." 和 "LNK1120 1 unresolved externals [in myFile]"

我希望我需要弄清楚如何包含我需要的实际 header 文件,but the Windows docs do not say (and Wikipedia 说大多数 child header 不能单独包含在内,所以这可能是个问题)。

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>    // Windows specific libraries for collecting software metrics.
#include <Psapi.h>

我已经花了一整天的时间来解决这个问题,任何帮助都将不胜感激,因为 Windows 文档非常无用,我非常沮丧。如果这是一个愚蠢的问题,我深表歉意,但我经常为包含问题而苦恼。

终于想通了。

显然 psapi.lib 并没有被 Visual Studio 自动链接(尽管 Windows 实用程序库是...)。您必须进入 properties/linker/input 并手动将库添加为依赖项。如果找不到库位置,请在 C/C++ 中手动添加目录作为搜索目录。

您还必须有#define WIN32_LEAN_AND_MEAN。

希望对您有所帮助,如果以后有人需要这方面的帮助,请在此处发表评论。

解决方案归功于@RbMn 和@Scheff,谢谢大家!