c++ - C++ 中 C 库的范围 - <X.h> 与 <cX>

标签 c++ gcc gnu

The C++ Programming Language : Special Edition 在第 431 页指出...

For every header < X.h > defining part of the C standard library in the global namespace and also in namespace std, there is a header < cX > defining the same names in the std namespace only.

然而,当我在 风格中使用 C 头文件时,我不需要限定 namespace 。例如……

#include <cmath>
void f() {
  double var = sqrt( 17 );
}

这会很好地编译。尽管书中说使用 header 仅在 std 命名空间中定义名称,但您可以在不限定命名空间的情况下使用这些名称。我在这里缺少什么?

附言使用 GNU.GCC 编译器

最佳答案

Stephan T. Lavavej,MSVC 团队的一员,在他的一篇博文 (http://blogs.msdn.com/vcblog/archive/2008/08/28/the-mallocator.aspx#8904359) 的评论中解决了这种情况的现实情况(以及对标准的一些改进):

> also, <cstddef>, <cstdlib>, and std::size_t etc should be used!

I used to be very careful about that. C++98 had a splendid dream wherein <cfoo> would declare everything within namespace std, and <foo.h> would include <cfoo> and then drag everything into the global namespace with using-declarations. (This is D.5 [depr.c.headers].)

This was ignored by lots of implementers (some of which had very little control over the C Standard Library headers). So, C++0x has been changed to match reality. As of the N2723 Working Paper, http://open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2723.pdf , now <cfoo> is guaranteed to declare everything within namespace std, and may or may not declare things within the global namespace. <foo.h> is the opposite: it is guaranteed to declare everything within the global namespace, and may or may not declare things within namespace std.

In reality and in C++0x, including <cfoo> is no safeguard against everything getting declared in the global namespace anyways. That's why I'm ceasing to bother with <cfoo>.

This was Library Issue 456, http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#456 .

(C++0x still deprecates the <foo.h> headers from the C Standard Library, which is hilarious.)

我 100% 同意 Lavavej,除了我从未尝试过非常小心地使用 <cfoo> 样式的 header ,即使是在我第一次开始使用 C++ 时也是如此——标准的 C header 太根深蒂固了——而且从来没有真正的使用它们的世界问题(显然使用 <cfoo> 样式 header 从来没有任何现实世界的好处)。

关于c++ - C++ 中 C 库的范围 - <X.h> 与 <cX>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2118422/

相关文章:

c++ - 将可执行文件与静态库的完整路径链接起来

c++ - QThreadPool & QRunnable & 静态函数

c++ - 在 visual studio 2013 中必须同时使用 pthreadVC2.lib 和 pthreadVC2.dll 吗?

c++ - OpenGL- 没有光 C++ 的平面着色

c++ - 在生产环境中使用 PGO(profile-guided optimization)的风险

c++ - 为什么 std::variant 在 GCC 8.5 和 GCC 12.1 上对于 `const char *` 文字的行为不同?

c++ - 初始化 union 内的结构 (C++)

linux - Makefile 中的变量泄漏

c++ - GNU _M_ 前缀背后的心态

assembly - ELF 格式的可重定位符号(汇编语言)