c++ - 在 C++ 中使用 C 头文件时,我们应该使用 std::或全局命名空间中的函数吗?

标签 c++ language-lawyer std

C 在某种程度上,不完全是 C++ 的一个子集。所以我们可以通过稍微改变名称(stdio.h to cstdio, stdlib.h)来使用C++中的大部分C函数/头文件> 到 cstdlib)。

我的问题实际上是一种语义问题。在 C++ 代码中(使用最新版本的 GCC 编译器),我可以调用 printf("Hello world!");std::printf("Hello world!"); 它的工作原理完全相同。在我使用的引用文献中,它也显示为 std::printf("Hello world!");.

我的问题是,是否更喜欢在 C++ 中使用 std::printf(); ?有区别吗?

最佳答案

来自 C++11 标准(重点是我的):

D.5 C standard library headers [depr.c.headers]

  1. For compatibility with the C standard library ...
  2. Every C header, each of which has a name of the form name.h, behaves as if each name placed in the standard library namespace by the corresponding cname header is placed within the global namespace scope. It is unspecified whether these names are first declared or defined within namespace scope (3.3.6) of the namespace std and are then injected into the global namespace scope by explicit using-declarations (7.3.3).
  3. Example: The header <cstdlib> assuredly provides its declarations and definitions within the namespace std. It may also provide these names within the global namespace. The header <stdlib.h> assuredly provides the same declarations and definitions within the global namespace, much as in the C Standard. It may also provide these names within the namespace std.

不推荐使用 «name.h» header ,它们已被确定为从 future 修订版中删除的候选者。

因此,我建议包含 «cname» header 并使用 std 中的声明和定义命名空间。

如果您出于某些原因必须使用 «name.h» header (已弃用,见上文),我建议您使用全局命名空间中的声明和定义。

换句话说:喜欢

#include <cstdio>

int main() {
    std::printf("Hello world\n");
}

结束

#include <stdio.h>

int main() {
    printf("Hello world\n");
}

关于c++ - 在 C++ 中使用 C 头文件时,我们应该使用 std::或全局命名空间中的函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32606023/

相关文章:

c++ - 检查N及其双重存在

c++ - 基于现有实例创建类的新实例

c++ - 是否假定C/C++中的所有函数都返回?

c# - volatile 是否会阻止引入的读取或写入?

c++ - 内联 constexpr 函数定义是否合法? gcc (ok) vs clang (error)

c++ - 编译时检查模板类型 C++

c++ - 调用 CMD.exe 后立即返回的 VC++ std::system() API

python - 将 Python 算法翻译成 C++ 时遇到困难

c++ - 释放存储在 std::queue 中的堆指针

c++ - C stdlib/stdio 的阴影函数