Implementing not-quite-namespaces in C
February 28, 2010 on 11:24 am | In General | 1 CommentHi, all!
A few days ago i came across a trick in C. It isn’t new, but i hadn’t seen it used quite this way before and i wanted to share it…
Background: i have several mini-libraries which i tend to copy directly in to other projects. It has happened that i then use two other libraries together, and both of them internally use the same underlying mini-library. In some cases i want each to continue to use their own copy (maybe a different/incompatible version), but not collide with the other copy. Here’s one way to do it…
In the lib’s main header, before we declare any of its API:
#if !defined(MY_NS) # define MY_NS(X) my_namespace_prefix_ ## X #endif
We then declare our types and functions using that macro:
int MY_NS(func1)( ... );
struct MY_NS(type1) { ... };
And throughout the implementation and client code we use:
int x = MY_NS(func1)( ... );
Each library which wants to import and rename the API then simply has to redefine MY_NS while building the included mini-library.
The major down-side is that this construct makes reading the docs through tools like doxygen more difficult.
Happy hacking!
Powered by WordPress with Pool theme design by Borja Fernandez.
Entries and comments feeds.
Valid XHTML and CSS. ^Top^