Reputation:
Why I don't need to include cstdlib and how do I disable this? I'm using Code::Blocks with GCC compiler on Windows 7.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
cout << "Hello" << endl;
system("pause");
return 0;
}
Upvotes: 6
Views: 1047
Reputation: 3249
You don't need to include <cstdlib>
because it (or the part of it containing system()
) was included by <iostream>
. It is unspecified whether or which other (standard) headers are included by standard headers. You cannot disable this behavior but should be aware of it to avoid portability problems between different standard library implementations.
You should not depend on this behavior and include <cstdlib>
yourself. You should also use std::system
instead of the global system
. Functions from <c*>
headers are only guaranteed to be in the std
namespace (the global ones, on the other hand, in the <*.h>
headers).
Upvotes: 7
Reputation: 1374
I am using MS Visual Studio 2012 and in it, <iostream>
includes <istream>
which includes <ostream>
which includes <ios>
which includes <xlocnum>
. <xlocnum>
includes <cstdlib>
, so your program indirectly includes <cstdlib>
Although the sequence of includes might be different in other compilers and/or implementations, the reason that this code runs is that <iostream>
, either directly or indirectly includes <cstdlib>
.
It should be noted the the libraries that iostream
includes are implementation-specific and the code might not compile in some other compiler. As a general rule, the libraries that a header file includes are not usually well-documented or part of the standards, so do not rely on indirect includes. If you need a library, include it directly and, since standard libraries are include guarded, no significant overhead will be inflicted on your program's compilation or run-time.
Upvotes: 3