C++ code compiles without include

后端 未结 2 1605
小鲜肉
小鲜肉 2020-12-11 19:52

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 

using std:         


        
相关标签:
2条回答
  • 2020-12-11 20:31

    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).

    0 讨论(0)
  • 2020-12-11 20:52

    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.

    0 讨论(0)
提交回复
热议问题