C ++ 11 includes <cstdlib> at a time when C ++ 03 will not?

Take a look at this tiny program.

#include <iostream> int main(){ int var = atoi("-99"); //convert string to int var = abs(var); //takes absolute value std::cout << var+1 <<'\n'; //outputs 100 return EXIT_SUCCESS; } 

Compilation generates the following error messages:

 $ g++ -o main main.cpp main.cpp: In function 'int main()': main.cpp:5:13: error: 'atoi' was not declared in this scope main.cpp:6:16: error: 'abs' was not declared in this scope main.cpp:9:10: error: 'EXIT_SUCCESS' was not declared in this scope 

I see. They all exist in the "cstdlib" header, which I forgot to include.
However, compiling with:

 $ g++ -std=c++0x -o main main.cpp 

no problem.


looking at the source of the cstdlib header, I see the following code below:

 #ifdef __GXX_EXPERIMENTAL_CXX0X__ # if defined(_GLIBCXX_INCLUDE_AS_TR1) # error C++0x header cannot be included from TR1 header # endif # if defined(_GLIBCXX_INCLUDE_AS_CXX0X) # include <tr1_impl/cstdlib> # else # define _GLIBCXX_INCLUDE_AS_CXX0X # define _GLIBCXX_BEGIN_NAMESPACE_TR1 # define _GLIBCXX_END_NAMESPACE_TR1 # define _GLIBCXX_TR1 # include <tr1_impl/cstdlib> # undef _GLIBCXX_TR1 # undef _GLIBCXX_END_NAMESPACE_TR1 # undef _GLIBCXX_BEGIN_NAMESPACE_TR1 # undef _GLIBCXX_INCLUDE_AS_CXX0X # endif #endif 

I'm not sure if this is important or not. Full header file code here

My last question is, does the new standard guarantee that all cstdlib will be included in the global namespace when you turn on iostream?

I can not find documentation on this. Appears to me like that, do you think it?

 gcc (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1 
+7
source share
1 answer

My last question is that the new standard ensures that all cstdlib will be included in the global namespace when you turn on iostream?

Not. You must #include yourself if you need its functionality. If you get "free" using <iostream> , this is the sign your <iostream> header requires, but then you rely on the implementation detail of your C ++ library.

Btw., #include <cstdlib> not guaranteed that C functions are passed to the global namespace (although this usually happens in C ++ implementations); it can put them in the std :

Except as specified in paragraphs 18-30 and Appendix D, the contents of each cname header shall be the same as the contents of the corresponding header name.h , as specified in the standard C library (1.2) or in C Unicode TR, as appropriate , as if by inclusion. However, in the C ++ standard library, declarations (with the exception of names that are defined as macros in C) are in the namespace (3.3.6) of the std . It is not known whether these names will be first declared in the global namespace and then inserted into the std namespace using explicit using -declarations (7.3.3).

(standard, section 17.6.1.2)

+15
source

All Articles