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?
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.
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.
精彩评论