Fog Creek Software
g
Discussion Board




Avoiding namespace collisions in C libraries?

Hi.

I'm writing a C library and I was wondering how far I should go to try to prevent namespace collisions. I'm of course going to use a module name prefix (probably about three to four letters long) for each non-static function, but I was wondering what I should do for preprocessor macros. I'm going to have quite a few of them, and I know redefining a macro results in a warning with many (e.g., GCC) compilers, and some of the #defines I'm going to be using will be quite short (some even just two to three characters long). Would you recommend extending the module namespace prefix to macros too? Do you prefer one style over another (e.g., for libpepsi, CAFFEINE_FREE instead of the safer PEPSI_CAFFEINE_FREE)? (This would be in addition to any category-specific postfix or suffix I'd add to the macro name, like ERR_* for error codes or CLR_* for colors, resulting in, for example, PEPSI_ERR_OUT_OF_FRUCTOSE.)

The Great Minneapolis Sanitation Worker Riots of 1978
Sunday, March 21, 2004

If the macros are defined in header files, pseudo-namespace information should be included in them (especially for two or three letter macro names!).  I'm very paranoid about name conflicts, especially because I hate having some other programmer come to my desk saying, "hey I'm using your library but it doesn't work with X, so I looked at your header file and you just need to make this little change."

K
Sunday, March 21, 2004

Yes. Use prefixes for everything. Avoid the temptation to make names "helpfully" short, and don't worry too much if it looks a bit ugly.

(The names can get a bit long, but in my experience that doesn't matter *too* much, unless you're trying to squeeze lots into a line. Unless you're writing code that does some common formula, that probably isn't a good idea anyway.)

Insert half smiley here.
Sunday, March 21, 2004

My general style is to have a prefix for function names,
and a capitalized form of the prefix for macros.  Also, a
good library should have a simple API header, including
macros used by the API, that can stand alone without
needing to refer to internal header files.  By doing this,
it is easy to use your library and you can do internal
changes at will, without breaking user code, as long as the
spec for your API entry points stays backward compatible.

x
Monday, March 22, 2004

"redefining a macro results in a warning with many (e.g., GCC) compilers"

The C standard mandates a warning if the macro is redefined to a different value.  The warning can be
avoided by #undefing the symbol first.

Should macro names as well as global symbols be prefixed?  Yes, absolutely ... why in the world not?

jqb
Tuesday, March 23, 2004

*  Recent Topics

*  Fog Creek Home