46

I have a C header that was written to compile as both C and C++ (it only uses features from the common subset, and uses that extern "C" thing).

Problem is, that header declares stuff in the global namespace. I'd rather avoid that for the usual reasons. I thought about doing this:

namespace foo {
#include <foo.h>
}

Is doing this a good idea? Do I have alternatives that don't include editing the header file?

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510

2 Answers2

49

No, it’s a bad idea. With C++ declarations, it's likely to introduce linker errors as identifiers get declared in the wrong namespace. With C declarations, it works, but it may hide clashes between identifiers in the global namespace (which you were trying to avoid, I guess) until link time; it doesn't really put the identifiers in a namespace.

A better idea would be to put your own identifiers in a namespace and avoid defining anything but main in the global one.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • +1 I actually ran into a problem like this because a certain open source project decided to do [exactly this](http://stackoverflow.com/questions/6006602/pulling-c-c-standard-library-into-your-project-namespace-good-idea). The result was that I had to dig through ***numerous*** project and std headers to figure out the root cause. I managed to resolve it but in the end this just ends up being another porting issue to worry about. – greatwolf Jul 12 '11 at 20:41
  • I had a feeling this wasn't quite right, but I couldn't say why. I'm glad I decided to ask here :) – R. Martinho Fernandes Jul 12 '11 at 20:45
  • 1
    Congrats on the gold badge :) – R. Martinho Fernandes Jul 12 '11 at 22:15
  • 1
    Example of hiding of name clashes until at least assembly (code generation) time: http://coliru.stacked-crooked.com/ – Cheers and hth. - Alf Nov 10 '15 at 04:00
5

I did this kind of "place it in a namespace" for <windows.h> in the late 1990's.

Although not with complete support: it was on the principle of adding support for whatever next I needed when I needed it.

The key to make that work was to check which C library headers were included, and make sure to include them first. It boiled down to 4 such headers, IIRC. Microsoft's love of macros made things difficult, though.

So it can be done in practice for C headers (or C++ restricted to the C-like subset), but at cost of updating your wrapper for every new version of the wrappee, Which is impractical and/or very costly. Not to mention laborious.

In conclusion, no, it's not a good idea. :-)

Speaking from experience.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331