0

I am currently building my first more complex C++ program that contains an own namespace. Of course, I use several imports. Ehat I found to be strange is that function included with eg.

#include <math.h>

can be accessed within the workspace

a = cos(b)

where the cos function is part of math.h. On the other hand functions included with eg.

#include <fstream>

must be accesed via

std::ifstream

or similar. I would like to understand this

Glostas
  • 1,090
  • 2
  • 11
  • 21
  • I agree with the answer. Note that, if you 'can't live with this', you might say `namespace math { #include }`. This works with C headers, usually doesn't with C++ ones. – lorro Jul 25 '16 at 11:14
  • I agree with the duplicate one. I wasn't aware of this c prefix .h thing so I havent searched for it – Glostas Jul 25 '16 at 11:29

1 Answers1

4

C++ standard library includes most of the C library (there are some hazy details around optional parts of the C library).

Since C has no concept of namespacing, everything included from the C library will be in the global namespace. Since <math.h> is a C header, its functions are put into global namespace.

Everything included from the C++ standard library will be in the std:: namespace, like std::ifstream when you included <fstream> header.

Where it gets fun, are aliases. As an example, <math.h> can also be included as <cmath>. The idea behind this was that you select whether you want the C symbols in global namespace (including <math.h>) or in the std:: namespace (including <cmath>), but this didn't work out and generally if you include the C++ version of the header (ie <cmath>), you will get both.

Generally, if a header can either be included via <foo.h> or via <cfoo>, its a C header. C++ standard library headers do not have these aliases (except when you have to deal with non-standard things like iostream.h that apparently still exist on some platforms).

Xarn
  • 3,460
  • 1
  • 21
  • 43