gpt4 book ai didi

c++ - 在头文件和 cpp 文件中包含一个库

转载 作者:太空狗 更新时间:2023-10-29 21:32:32 26 4
gpt4 key购买 nike

我是 C++ 新手。我在头文件和 cpp 文件中都看到了包含库文件(例如 string)的代码。如果不使用 #ifndef 是否会导致重复代码?或者预处理器是否足够聪明以忽略它。在两个文件中包含相同的库是否正常?

测试.h

#include <string>
.
.
.

测试.cpp

#include <string>
#include "test.h"
.
.
.

最佳答案

Is it normal to include the same library in both files?

是的。将一个文件头包含到多个文件中是正常的。

无论何时使用标题中的声明,都应该包含该标题。如果你使用 std::stringtest.h , 那么你应该包括 <string>test.h .如果你使用 std::stringtest.cpp , 那么你应该包括 <string>test.cpp .是否<string>恰好包含在 test.cpp 包含的标题之一中无关紧要,不应依赖。

Will this cause duplicate code if #ifndef is not used?

如果一个 header 没有 header 保护,那么多次包含它确实会导致其内容重复,是的。

or is the preprocessor smart enough to ignore it.

预处理器不会忽略任何包含。每个包含将被处理。预处理器可能足够聪明,可以优化包含它知道由于包含保护而为空的 header 。

关于c++ - 在头文件和 cpp 文件中包含一个库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54837486/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com