Consider the following code that doesn't compile:
#include <map>
//#include <stdexcept> // uncommenting this works
int main() {
std::map<int, int> test;
try {
test.at(10);
} catch(std::out_of_range& e) {
}
return 0;
}
Why does std::map not include std::out_of_range, even if it uses it? (The .at() can throw a std::out_of_range).
When I also include <stdexcept> it compiles, and works fine.
Whether a standard header does include another header is an implementation detail unless explicitly specified.
With templates its a little more involved, but just to point you in some direction, consider this toy example:
// header: my_map.h
struct my_map {
int at(int);
};
Only in the source file the header for the exception has to be included:
// source: my_map.cpp
#include <stdexcept>
int my_map::at(int) {
throw std::out_of_range("bla");
}
std::map surely looks different but it may hide the exception from the header as well.
Is it also ok for a header to not include a decl for std::pair
The headers that are specified to be included via <map> are <compare> (since C++20) and <initializer_list> (since C++11). Nothing more.
<map> may include other headers and thats one of the "implementation details" mentioned in comments. The part of the standard that explicitly allows standard headers to include others is [todo.put reference here].
The simple rule of thumb that avoids such headace is: Include what you use.
but throwing std::out_of_range is not an "implementation detail" - it is part of the specification of std::map!
Consider that this code compiles with gcc 10.2:
#include <map>
int main() {
std::map<int, int> test;
try {
test.at(10);
} catch(...) {
return 1;
}
return 0;
}
The out_of_range exception is thrown and catched, and 1 is returned. We know what at may throw and catch(...) will catch it, yet no include is needed for the exception.
On the other hand, the same compiler rejects your example, but compiles it when we add a seemingly unrelated header:
#include <map>
#include <sstream> // why this?
int main() {
std::map<int, int> test;
try {
test.at(10);
} catch(std::out_of_range& e) {
}
return 0;
}
However, this only works by coincidence. Apparently <sstream> does include <stdexcept> somewhere along the line. But this may change with compiler version or between differernt compilers.
The implementation of std::map doesn't have to be all in the header file. Yes this is a class template, but it is free to use any internal non-template components.
Consequently, the header file doesn't have to mention std::out_of_range (it may well be hidden inside one of those non-template components) and so doesn't have to have its definition visible anywhere, or behave as if it includes <stdexcept>. It is explicitly allowed to, but there is no implicit or explicit obligation in the standard for it to do so. So it might, or might not.
In fact g++-9 behaves as if <map> includes <stdexcept>, and g++-10 does not, and in both cases they are correct.
Why does std::map not include std::out_of_range
Assuming you are using GCC 10, GCC developers decided to optimize header dependencies in C++ Standard Library code. From Porting to GCC 10:
Header dependency changes
Some C++ Standard Library headers have been changed to no longer
include the <stdexcept> header. As such, C++ programs that used
components defined in <stdexcept> or <string> without explicitly
including the right headers will no longer compile.
Previously components such as std::runtime_error, std::string and
std::allocator were implicitly defined after including unrelated
headers such as <array> and <optional>. Correct code should include
the appropriate headers for the classes being used.
Also from GCC 10 Release Notes:
Reduced header dependencies, leading to faster compilation for some
code.
I've been puzzled by this for a while. To test this out, I made a simple program that just creates a std::string variable and prints it out to the screen. However, it doesn't include <string.h>.
#include <iostream>
using namespace std;
int main()
{
string name = "Test";
cout << name << endl;
return 0;
}
What confuses me is that this program compiles and runs perfectly. Right now I'm using the clang compiler that came with the XCode Developer Tools. Is this intended behavior? I hope this question isn't too ridiculous since I just started learning C++.
The reason you do not need to include the #include <string.h> header file is because when you include the #include <iostream> header file it includes std::string.
However, do not rely on it. What may work on your compiler may not work on another. Always include the proper header files.
To edit your example this is how you should use it:
#include <iostream>
#include <string>
int main()
{
std::string name = "Test";
std::cout << name << std::endl;
return 0;
}
Also note: why you should not use using namespace std;.
Why does my program compile successfully if I don't include <string.h>?
Because you don't use any definition / declaration from <string.h>.
program compiles and runs perfectly ... Is this intended behavior?
It is incidental behaviour.
There are no guarantees that one standard header wouldn't include other standard headers. It just so happens that <iostream> included <string> in this particular version of the standard library. Since there is no guarantee for this, it would be a mistake to rely on such transitive inclusion.
Since the namespace std already has the c++ libraries that contain the function definitions(if i am right), then why do we include header files on top of it??. Since namespace std includes the c++ standard libraries, I don't see a reason to include the declarations of it separately.
When you do #include <iostream> it causes a set of classes and other things to be included in your source file. For iostream, and most of the standard library headers, they place these things in a namespace named std.
So the code for #include <iostream> looks something like this:
namespace std {
class cin { ... };
class cout { ... };
class cerr { ... };
class clog { ... };
...
}
So at this point, you could write a program that looks like:
#include <iostream>
int main() {
std::cout << "hello\n";
return 0;
}
Now, some people feel that std::cout is too verbose. So they do:
#include <iostream>
using namespace std;
int main() {
cout << "hello\n";
return 0;
}
Personally, I'd recommend against this, and if you really feel that std::cout is too verbose, then I'd suggest that you use a smaller using statement.
#include <iostream>
using std::cout;
int main() {
cout << "hello\n";
return 0;
}
If you're wondering why I would recommend against using namespace std, then I would forward you to the following two other posts on stackoverflow:
C++ Distance Function Keeps Returning -1
Why is "using namespace std" considered bad practice?
The compiler itself does not have the definitions of the things that are in any namespace (whether it is std or some other namespace). That is the role of source files and header files.
What using namespace std; tells the compiler is that "If you can't find some name in the current namespace, go look in the std namespace as well".
What #include <iostream> tells the compiler is that you want the contents of the header called iostream to be included in your sources. This will provide the compiler with code to do cin, cout and a lot of other related functionality. The content of this file is declared like namespace std { ... all the stuff goes here ... }.
The usage of namespace allows someone else, working in namespace math; to not have to worry about "Hmm, what do I do now, I need a counter for number of entrances, let's call it cin - but hang on, is that ever used anywhere?".
This may not be the greatest of examples, but in large projects, it gets increasingly hard to keep track of things and what names they have. And C++ is a language intended for large projects of millions of lines of code - and now it starts getting hard to remember if you've used a particular name or not. Namespaces make sure that you don't have to worry about it outside of a particular namespace.
(Oh, and in my code, I tend to not use using namespace std;, but write std::cout << "Hello, World!" << std::endl; - this helps to make it clear that the cout I'm using here is the std one, and not something else. This is particularly useful when you have several namespaces with similar things, like in my own compiler, where I have my compiler with it's functionality, the std namespace providing some things, and llvm compiler things - if I were to stick using namespace llvm; at the beginning of the code, it would be very hard to track whether Type* p = ...; is from LLVM or some part of my own code.)
...why do we include header files on top of it???
Yes, there is some big confusion here.
Namespaces
Namespaces are a method to categorize or group together, symbols such as function names.
Namespaces are design to prevent name conflicts between different software components, such as libraries.
Functions that are a part of the standard language, are grouped under the namespace std.
The C++ language provides statements to reduce the amount of typing when using namespaces. One of these is the using statement.
Header (include) Files
When you write a program, the compiler is not required to automatically include all the symbol definitions, such a function declarations. You need to tell it which functions you plan on using.
For example, I could write a program without using the sort or advance functions from the algorithm group. Therefore I would not include the header file algorithm.
The C++ language is designed to be "use what you need", in other words, we can create small programs by only including the functions we need.
Other Platforms
By the way, there are many other platforms out there than the one you are using.
Some platforms need to fit in small memory areas and may not have a keyboard or display (such as embedded controllers).
So remember, C++ was defined to support platforms from the small and constrained to the large and virtually unconstrained system.
Thus the requirement to "include only what you need" theme.
Summary
In summary, since the C++ languages doesn't automatically, magically, provide the definitions of the entire library, including the template library, you need to tell the compiler which groups of functions you want to use. This allows for quicker compilations since only the required header files are specified.
Note: Some shops and library supplies like to use the Monolith include system. This means that they have one include file that includes their entire library, whether you use one function or many. The windows.h is a classic example. One detriment is that when one header file is changed, everything needs to be rebuilt. With separated include files, only the components that include the changed header file need to be rebuilt.
Use of preprocessor directive #include is as old as c++ itself. And its not going away any sooner.In C++ namespace Doesn't import anything into your program, it just defines the scope of your particular header file's function.So, both are required. Click hereto understand why use namespace.
Your question is: namespace std has all the definitions of functions/classes of iostream library. So simply using using namespace std is enough to call or use cout or all other functionalities of iostream library. Why do we have to use line #include <iostream>? It seems redundant.
Roughly we can think that iostream library has two files: header and implementation/source file. These two files have a namespace called std. The header file only contains the declarations or forward declarations of classes or functions or variables that iostream library is going to use and these declarations or forward declarations are under the std namespace. The implementation file contains the actual implementations of the classes or functions or variables and these implementations are under the std namespace; this file is also called the source file.
So if you only use using namespace std without #include <iostream> in your main.cpp file compiler will search std namespace in your main.cpp file, but it is not here. You will get compiler error.
Now if you include this #include <iostream> line in your main.cpp, preprocessor will go iostream's header file and copy the std namespace along with its code into our main.cpp. And linker will link the precompiled(as iostream is a SLT so it comes with compiler with prebuilt) source/implementation file of iostream to your main.cpp. Now to use functions or variables of iostream that sit under std namespace in main.cpp we have to use scope resolution operator(::) to tell the compiler that cout, cin and other functionalities of iostream sit at std namespace. Thus we simply write like this: std::cin, and std::cout.
Now typing std:: seems redundant to some people so they tell the compiler by using this using namespace std "Hey compiler, if you don't find any variables/functions/classes in global/current namespace go look in the std namespace." Though this is not the best practice but that is another topic to discuss. Therefore your assumption that std namespace contains all the definitions of all SLT's functions/classes/variables of C++ is not correct in most cases, but std namespace only contains the declaration from STL is the correct assumption.
Here is a dummy implementation how iostream libray is added to our code files:
iostream.h:
// This is header file that only contains the
// functions declarations.
namespace std_dum
{
int add(int x, int y);
int mult(int x, int y);
}
iostream_dum.cpp:
// This is source file of iostream_dum.h header
// which contains the implementation of functions.
#include "iostream_dum.h"
namespace std_dum
{
int add(int x, int y)
{
return x + y;
}
int mult(int x, int y)
{
return x * y;
}
}
main.cpp :
#include <iostream>
#include "iostream_dum.h"
int main()
{
std::cout << std_dum::add(100, 200) << '\n';
std::cout << std_dum::mult(100, 200) << '\n';
return 0;
}
To see what happens to our main.cpp file after preprocessing run this command: g++ -E main.cpp iostream_dum.cpp.
Here is roughly our main.cpp looks like:
namespace std_dum
{
int add(int x, int y);
int mult(int x, int y);
}
int main()
{
std::cout << std_dum::add(100, 200) << '\n';
std::cout << std_dum::mult(100, 200) << '\n';
return 0;
}
namespace std_dum
{
int add(int x, int y)
{
return x + y;
}
int mult(int x, int y)
{
return x * y;
}
}
For the sake of clarity, I discarded all the codes that the preprocessor copied from #include <iostream>.
Now it should be pretty clear.
I am very curious why I can use the math functions in C++ without including the "math.h". I can't find an answer with google search.
Here is the simple code I am executing. Everything is compiling and running.
#include <iostream>
using namespace std;
int main()
{
const float PI = acosf(-1);
cout << PI << endl;
return 0;
}
Any standard header is allowed to include any other standard header.
if you would compile the same with gcc-4.8 it would complain.
Keep in mind that this is not something to rely on if you want your code to be portable and compilable on different versions of the same or different compilers.
I want to use "Dev-C++" for compile c++ codes.
So I download and install it, and write this code:
#include <iostream.h>
main () {
cout << "124";
}
but when I compiled it, it said:
In file included from
E:/Dev-Cpp/include/c++/3.4.2/backward/iostream.h:31,
from [myfile path]\Untitled1.cpp:1:
E:/Dev-Cpp/include/c++/3.4.2/backward/backward_warning.h:32:2:
warning: #warning This file includes
at least one deprecated or antiquated
header. Please consider using one of
the 32 headers found in section
17.4.1.2 of the C++ standard. Examples include substituting the header
for the header for C++ includes,
or instead of the
deprecated header . To
disable this warning use
-Wno-deprecated.
After I saw errors, I change my code to this code:
#include <iostream>
main () {
cout << "124";
}
but it said again that errors.
I compile first code easily in Turbo C++, BUT in Dev-C++ ...
What can I do?
First, make sure you write out the full definition of main, including the int return type. Leaving out the return type is an old, antiquated practice which doesn't fly these days.
Second, in the new-style headers—the ones missing the .h extension—the standard library is under the std namespace. There are two ways to make your program work:
1. Add an std:: qualifier to cout.
#include <iostream>
int main () {
std::cout << "124";
}
2. Add a using declaration to allow unqualified references to the std namespace.
#include <iostream>
using namespace std;
int main () {
cout << "124";
}
Make sure you put int in front of main () {
I believe any C/C++ program's main() function is required by POSIX and the appropriate language standards to return an int (someone correct me if I'm wrong).
EDIT: Also, be sure to include using namespace std; above int main ().