为什么两个&#34; std :: printf&#34;和&#34; printf&#34;在C ++中使用<cstdio>而不是<stdio.h>时编译?</stdio.h> </cstdio>

时间:2015-01-30 00:02:59

标签: c++ namespaces header-files

据我所知,cxyz表单的标题与xyz.h相同,唯一的区别是cxyzxyz.h的所有内容放在名称空间{ {1}}。为什么以下程序都在GCC 4.9和clang 6.0上编译?

std

和第二个程序:

#include <cstdio>

int main() {
    printf("Testing...");
    return 0;
}

FILE结构也是如此:

#include <cstdio>

int main() {
    std::printf("Testing...");
    return 0;
}

FILE* test = fopen("test.txt", "w");

都工作。

到目前为止,我一直认为最好使用std::FILE* test = std::fopen("test.txt", "w"); cstdio等,而不是使用非命名空间的对应物。但是,以上两个以上哪个程序是更好的做法?

其他C函数也是如此,例如memset(来自cstring),scanf(也来自cstdio)等。

(我知道有些人会问为什么我在C ++程序中使用C IO;这里的问题不是专门的C IO,而是在调用命名空间之前是否应该编译而没有专门指定cstring C函数。)

1 个答案:

答案 0 :(得分:6)

该标准允许编译器将名称注入全局名称空间。

这样做的一个原因是它允许<cstdio>的实施:

#include <stdio.h>

namespace std
{
    using ::printf;
    using ::fopen;
    // etc.
}

因此编译器/库供应商不必编写和维护这么多代码。

在您自己的代码中,始终使用std::using namespace std;等,以便您的代码可以移植到不将名称注入全局命名空间的编译器。