2

Assuming I have the code snippet like this:

#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
printf("%d",5);
}

It compiles and runs normally on my Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn) compiler, however it fails on gcc version 4.4.5 (Debian 4.4.5-8), saying it doesn't recognize "printf" function. Professors at my Uni use the latter and today they said that my program doesn't work.

My question is - why does clang (run by g++ namefile.cpp on OS X 10.9) include "cstdio.h" automatically in this case?

PS. I am aware there are cin and cout streams in C++, and that would solve the problem, but my question is more theoretical and for future purposes of automatic includes.

4

1 回答 1

12

The standard C++ headers are allowed to include any other standard headers. Each implementation has the option to decide which headers get included by which others. You've included iostream, and that's allowed to include cstdio, but it's also allowed not to. Your version of Clang and your instructor's version of GCC have evidently exercised the option differently.

Best practice dictates that you explicitly include the headers you need; don't count on you implementation to implicitly include headers you haven't mentioned. It's liable to change from one release to another, and it affects portability.

于 2013-11-05T15:06:23.847 回答