为什么在包含iostream时可以使用printf()?

Why can I use printf() when including iostream?

本文关键字:printf 可以使 包含 iostream 为什么      更新时间:2023-10-16

这段代码即使在 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.hprintf放在全局命名空间中,这通常不是人们想要的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

cstdiostdio.h的C++包装器

所有突出显示的名称都是标准标头,ioscstdio之间的链依赖于编译器(在我的情况下,xlocknum是 VS2017 编译器的内部(