据我所知,cxyz
表单的标题与xyz.h
相同,唯一的区别是cxyz
将xyz.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函数。)
答案 0 :(得分:6)
该标准允许编译器将名称注入全局名称空间。
这样做的一个原因是它允许<cstdio>
的实施:
#include <stdio.h>
namespace std
{
using ::printf;
using ::fopen;
// etc.
}
因此编译器/库供应商不必编写和维护这么多代码。
在您自己的代码中,始终使用std::
或using namespace std;
等,以便您的代码可以移植到不将名称注入全局命名空间的编译器。