当多个文件需要 C++ 时,在何处插入#include

Where to insert an #include when multiple files need it C++

假设我有 4 个源文件 main、aux1、aux2 和 aux3,它们都使用字符串,因此需要 #include <string>

主要的将包括 3 个辅助,因为它将使用它的功能,但是 none 的辅助需要包括主要的或任何其他辅助。

我应该在哪里包含字符串,#pragma once 之类的东西如何帮助我解决这种情况?

Headers 应该包括他们使用的内容。背离这一点会导致长期的痛苦 运行。因此:

// aux1.h
#include <string>

// aux2.h
#include <string>

// aux3.h
#include <string>

// main.cpp
#include "aux1.h"
#include "aux2.h"
#include "aux3.h"

原则上,您可以在 main 中包含 <string>,然后再包含其他 header,这样即使其他 header 不包含,代码也会编译包括 <string>。然而,这是非常脆弱的,因为代码的正确性取决于包含的顺序。 auxX.h header 应该是正确的,而不管其他 header 是否已经包含在内。

[...] how could something like #pragma once help me with this situation?

你应该为你自己的 header 使用 header 守卫,虽然 <string> 已经有 header 守卫并且多次包含它不是你需要的东西担心。