为什么在包含iostream时可以使用printf()?
Why can I use printf() when including iostream?
这段代码即使在 C++11 标准下使用 minGW 编译器也能正常工作:
#include <iostream>
int main(int argc, char const *argv[])
{
printf("haha");
return 0;
}
为什么要这样做?我没有包括stdio.h
但我可以使用printf()
和rand()
等功能。它们是否包含在iostream
中?至少我没有发现它们包括在内。如果你说它包含在iostream
中,请给我看证据。
如果它有效与否,它是定义的实现。
该实现可能包含它所需的其他标头,但您作为开发人员不应依赖它,也应包括cstdio
这是访问std::printf
的保证方式。
包括stdio.h
printf
放在全局命名空间中,这通常不是人们想要的C++,所以坚持cstdio
。
您的实现似乎将printf
放在全局命名空间中,即使您只包含一个 C++ 标头。这很不幸,但这种情况也会发生。
证据:我的预处理器称为cpp
,我可以使用它来列出包含的头文件。我有这个程序,我称之为std.cpp
:
#include <iostream>
int main() {}
如果我使用cpp
列出所包含标题的一小部分
cpp -M std.cpp | tr -d '' | tr ' ' 'n' |
grep -E '^/[^.]+$' | awk -F/ '{print $NF}'
我在系统上收到以下C++标头:
iostream
ostream
ios
iosfwd
cwchar
exception
typeinfo
new
type_traits
cstdint
clocale
cctype
string
initializer_list
cstdlib
cstdio
cerrno
system_error
stdexcept
streambuf
cwctype
istream
是的,cstdio
在那里,其中还包括stdio.h
.
正如 Lyngmo @Ted所说,它的实现是定义的,通常包括<cstdio>
,就像<cstdlib>
一样。
我的<iostream>
头文件包括:
#include <bits/c++config.h>
其中术语包括:
/* Define if C99 functions or macros in <stdio.h> should be imported in
<cstdio> in namespace std for C++11. */
#define _GLIBCXX11_USE_C99_STDIO 1
和
/* Define if C99 functions or macros in <stdio.h> should be imported in
<cstdio> in namespace std for C++98. */
#define _GLIBCXX98_USE_C99_STDIO 1
<stdlib.h>
也是如此.
实施信息:
Thread model: posix
gcc version 9.2.0 (tdm64-1)
您可以打开包含文件并查看以下包含链:IOeStream=>iStream=>ostream=>iOS=>Xlocknum=>CSTDIO
cstdio是stdio.h的C++包装器
所有突出显示的名称都是标准标头,ios和cstdio之间的链依赖于编译器(在我的情况下,xlocknum是 VS2017 编译器的内部(
相关文章:
- 是否可以使C++类成为Objc类的委托
- 是否可以使一个类成为两个不同层次结构的子类?
- 是否有编译器标志可以使较新的 gcc 版本像旧版本一样构建
- C 可以使destuructor不称为班级成员和基类攻击方的灾难
- 可以使未命名的结构静态
- 是否可以使整数仅收到一个单个数字而不是两个接收输入
- C++:有哪些常规方法可以使代码更有效地用于大数字
- 是否可以使 std 容器使用默认运算符为新?
- LD_BIND_NOW可以使可执行文件运行得更慢?
- 是否可以使头文件使文本居中?- 在控制台中
- 有什么方法可以使核心忙碌等待
- 有没有一种技术可以使虚函数在所有派生类中强制重写?
- 有没有一种方法可以使全局函数/静态成员函数一次可呼出
- 是否有一种方法可以使此C 14递归模板在C 17中短
- 编写一个可以使二维数组平坦的函数
- 有哪些优化技巧可以使我的代码运行得更快
- 有没有更好的方法可以使此代码线程安全?线程局部静态似乎是一个生硬的工具
- 如果必须在同一向量上写入线程,是否可以使用线程
- 对于具有两个模板化变量的模板化类,是否可以使一个 var 引用另一个 var
- C 中的内容可以使Windows 8应用程序不在手臂上运行