Is it OK to put a standard, pure C header #include directive inside a namespace?

Posted by mic_e on Stack Overflow See other posts from Stack Overflow or by mic_e
Published on 2012-09-07T19:33:55Z Indexed on 2012/09/07 21:38 UTC
Read the original article Hit count: 164

Filed under:
|
|

I've got a project with a class log in the global namespace (::log).

So, naturally, after #include <cmath>, the compiler gives an error message each time I try to instantiate an object of my log class, because <cmath> pollutes the global namespace with lots of three-letter methods, one of them being the logarithm function log().

So there are three possible solutions, each having their unique ugly side-effects.

  • Move the log class to it's own namespace and always access it with it's fully qualified name. I really want to avoid this because the logger should be as convenient as possible to use.
  • Write a mathwrapper.cpp file which is the only file in the project that includes <cmath>, and makes all the required <cmath> functions available through wrappers in a namespace math. I don't want to use this approach because I have to write a wrapper for every single required math function, and it would add additional call penalty (cancelled out partially by the -flto compiler flag)
  • The solution I'm currently considering:

Replace

#include <cmath>

by

namespace math {
#include "math.h"
}

and then calculating the logarithm function via math::log().

I have tried it out and it does, indeed, compile, link and run as expected. It does, however, have multiple downsides:

  • It's (obviously) impossible to use <cmath>, because the <cmath> code accesses the functions by their fully qualified names, and it's deprecated to use in C++.
  • I've got a really, really bad feeling about it, like I'm gonna get attacked and eaten alive by raptors.

So my question is:

  • Is there any recommendation/convention/etc that forbid putting include directives in namespaces?
  • Could anything go wrong with

    • diferent C standard library implementations (I use glibc),
    • different compilers (I use g++ 4.7, -std=c++11),
    • linking?
  • Have you ever tried doing this?
  • Are there any alternate ways to banish the math functions from the global namespace?

I've found several similar questions on stackoverflow, but most were about including other C++ headers, which obviously is a bad idea, and those that weren't made contradictory statements about linking behaviour for C libraries. Also, would it be beneficial to additionally put the #include <math.h> inside extern "C" {}?

© Stack Overflow or respective owner

Related posts about c++

Related posts about namespaces