理解stdio.h与cstdio的异同

Last Updated: 2023-12-23 12:04:53 Saturday

-- TOC --

C++的进化演变很快,stdio.h也进化成了cstdio。虽然C++代码可以include这两个头文件中的任意一个,但在标准层面还是有一些区别的。

C++的标准头文件,都只有文件名,没有后缀!

C++标准文档的footnote(ISO 14882 in footnote 160)中,有这么一段注释:

The ".h" headers dump all their names into the global namespace, whereas the newer forms keep their names in namespace std. Therefore, the newer forms are the preferred forms for all uses except for C++ programs which are intended to be strictly compatible with C.

推荐学习:关于C++的namespace用法

也许是因为上面这段文字出现在标准的footnote中,很多C++编译器并没有这样实现,而是:

Most compilers completely fail to implement this correctly and put all the names into both namespaces (global and std) when using the new headers. As this is incorrect behaviour, it is quite likely to change in the future which means that code you write now may break on newer compilers as they get closer to the standard.

我测试g++的结果,与上面这段文字相符合,如果代码使用#include <cstdio>,代码中也可以直接使用printf(没有using namespace std)!

当然,C++标准同样也定义了如下这些新的来自C语言的头文件(可能不完整):

cassert ciso646 csetjmp cstdio ctime cctype 
climits csignal cstdlib cwchar cerrno clocale 
cstdarg cstring cwctype cfloat cmath cstddef

风格一致,都是前面加上字母c,表示这个头文件来自历久弥新的C语言,后面去掉.h,表示这是C++代码的引用。

本文链接:https://cs.pynote.net/sf/c/cpp/202208021/

-- EOF --

-- MORE --