Here's the code you need to implement this namespacing in your own code: #define NAMESPACE_MY_LIBRARY_WITH_A_LONG_NAME ml_ #pragma push_macro ("C") #pragma push_macro ("C_") #pragma push_macro ("N") #define C_(a,b) a##b #define C(a,b) C_(a,b) #define N(a) C(NAMESPACE_MY_LIBRARY_WITH_A_LONG_NAME, a) // All your code goes here, using N(NameOfThing) to name functions, types and variables. #pragma pop_macro ("C") #pragma pop_macro ("C_") #pragma pop_macro ("N")
Nice idea. AFAIK, `pop_macro` and `push_macro` pragmas are compiler specific extension though I think they are a quite popular. Btw.. it is worth to add `#ifndef NAMESPACE_... #define NAMESPACE... ml_ #endif` to set a default prefix and let the user set own.
You're right about the macros. I overlooked that since they're in GCC but I'll have to check on clang and vc compatibility. EDIT: According to my research, these pragmas are supported by GCC, VC and Clang. I initially had the namespace macro defined in the user's file before inclusion, but then if you do the usual separation of implementation and header in separate files, you need to copy that namespace definition to the library's implementation file. If you include the library in different translation units you also would have to copy it to them, so I think generally having it inside the library header is better.
Honestly I thought more than once about doing (pretty much) the same thing with my code. The only thing that stopped me was how this was going to interact with the various tools. Does jump to definition works? Etcetera etcetera... But I never bothered trying.
I tried multiple different ways of implementing namespaces and settled on this one partly because it works with intellisense 👍 Jump to definition et al all work 😊