gpt4 book ai didi

c++ - 为什么有些包含需要 .h 而有些则不需要?

转载 作者:IT老高 更新时间:2023-10-28 12:45:48 29 4
gpt4 key购买 nike

为什么 map 导入为#include <map> ,但 stdio 导入为 #include <stdio.h> ?

最佳答案

所有标准 C++ 头文件都不需要 .h到底。我在某处读到的概念是它们不需要是实际文件,即使我从未见过以另一种方式实现的实现 编辑: 实际上编译器内部函数应该考虑包含的头文件,但实际上并未将它们作为文件包含在内;查看@Yttrill的评论

对于 stdio.h事情,在 C++ 应用程序中你不应该包含 <stdio.h> ,但您应该包含 <cstdio> .一般来说,你不应该包含“普通”的 C 头文件,而是它们的 C++ 化的对应物,它们没有 .h最后,有一个c在前面并将其中定义的所有符号放在std 中命名空间。所以,<math.h>变成 <cmath> , <stdlib.h>变成 <cstdlib> ,等等。

一般来说,您应该使用 C++ 版本的 C header ,以避免污染全局命名空间(假设您不是将 using namespace std; 放在任何地方的人之一)并受益于一些 C++ 改进标准 C 头文件(例如,为某些数学函数添加了重载)。


一般来说,整个事情的实现只是通过在编译器查找头文件的目录中包含这些不带扩展名的文件来完成。例如,在我的 g++ 4.4 安装中,您有:

matteo@teoubuntu:/usr/include/c++/4.4$ ls
algorithm cstdarg functional sstream
array cstdatomic initializer_list stack
backward cstdbool iomanip stdatomic.h
bits cstddef ios stdexcept
bitset cstdint iosfwd streambuf
c++0x_warning.h cstdio iostream string
cassert cstdlib istream system_error
ccomplex cstring iterator tgmath.h
cctype ctgmath limits thread
cerrno ctime list tr1
cfenv cwchar locale tr1_impl
cfloat cwctype map tuple
chrono cxxabi-forced.h memory typeinfo
cinttypes cxxabi.h mutex type_traits
ciso646 debug new unordered_map
climits deque numeric unordered_set
clocale exception ostream utility
cmath exception_defines.h parallel valarray
complex exception_ptr.h queue vector
complex.h ext random x86_64-linux-gnu
condition_variable fenv.h ratio
csetjmp forward_list regex
csignal fstream set

C++ 化的 C 头文件理论上可能只是一个

namespace std
{
#include <original_C_header.h>
};

但一般来说,它们在处理特定于实现的问题(尤其是关于宏)和添加与 C++ 相关的功能(参见前面的 <cmath> 中添加重载的示例)时更加复杂。


顺便说一句,C++ 标准(§D.5)并没有说 <c***>标题应该表现得好像它们包含 <***.h> namespace std 中的标题指令,但相反:

For compatibility with the Standard C library, the C++ Standard library provides the 18 C headers [...] Each C header, whose name has the form name.h, behaves as if each name placed in the Standard library namespace by the corresponding cname header is also placed within the namespace scope of the name-space std and is followed by an explicit using-declaration (7.3.3)

请注意,此类 header 已被弃用(§C.2.1),因此这是您不应使用它们的主要原因:

C.2.1 Modifications to headers For compatibility with the Standard C library, the C++ Standard library provides the 18 C headers (D.5), but their use is deprecated in C++.

关于c++ - 为什么有些包含需要 .h 而有些则不需要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4404725/

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