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

标签 c++ printf iostream

这段代码即使在 C++11 标准下使用 minGW 编译器也能正常工作:

#include <iostream>

int main(int argc, char const *argv[])
{
    printf("haha");
    return 0;
}
为什么要这样做?我没有包含 stdio.h 但我可以使用 printf()rand() 之类的函数。它们是否包含在 iostream 中?至少我没有发现它们包括在内。如果你说它包含在 iostream 中,请给我看证据。

最佳答案

它的实现定义了它是否有效。
该实现可能包含它需要的其他 header ,但作为开发人员的您不应依赖它,并且也包含 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

关于c++ - 为什么在包含 iostream 时可以使用 printf()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62533672/

相关文章:

C++多线程程序: Segementation fault with variables defined as class members

用于命名空间限定的 C++ 预处理器 token 粘贴

c - 我刚刚设置的变量中 printf 期间的段错误

c - 在 c 中使用 sprintf 格式化字符串

c++ - Fstream 不保存文件中的最后一个单词,也不从文件中读取

c++ 链接器,如何链接 iostream 文件?

c++ - 为具有不同签名的函数的派生类设计基类

rust - 有没有办法在 println! 中设置宽度参数!有一个变量?

C++错误消息ostream未命名类型

C++ 内存地址递增