Subject: Plan for "namespaces" in C

From: Beni Cherniavsky <[email-masked]>
Date: Sun, 27 Jul 2003 22:24:21 +0300 (IDT)

I've got an ideas on how to program with sort of namespaces in C
without depending on others to adopt it.  Basic assumptions:

- I'm not in position to fight all the existing C compilers and
  linkers to support anything but the current single namespace.
- I'm even less in position to make all existing libraries declare
  explicitly that they export some namespace(s) to me.
- Good C style I expect from others who write libraries and that they
  expect from me is to use long prefixes, like ``g_io_channel_...`` or
  ``fribidi_...``.

There a useful namespaces mechanism for C should allow me to "import"
all names starting with a prefix (with a shorter prefix or directly),
without the library writer knowing of me doing it, and to write a
library whose external names are "exported" with a prefix without my
users having to know that I didn't write out all these prefixes in my
code...

The approach which seems best, because it doesn't require implementing
another preprocessing layer, is to automatically create header files
that do the necessary translations.  For example to "import
g_io_channel_ as gio_":

#define gio_unix_new g_io_channel_unix_new
#define gio_unix_get_fd g_io_channel_unix_get_fd
...

And the library could have been implemented with simply implementing
`unix_new`, `unix_get_fd`, etc., by putting at the start of the
implementation/header:

#define unix_new g_io_channel_unix_new
#define unix_get_fd g_io_channel_unix_get_fd
...

and at the end of the header (to not pollute the user's namespace):

#undef unix_new
#undef unix_get_fd
...

An extra bonus for this (except for clearer code) is that I can change
the naming conventions by changing a few import/export specs and
recompiling.

A few days ago I realized that I already have 95% of the work to
determine what names to export/import implemented for me, by the
programs ctags/etags!  The basic assumption is that any names I would
like to import/export from a library will be availiable from it's
header file (and the files it includes, recursively expanded with
``gcc -E``) - there is no need to consider prototype-less use nowdays.

Now it won't be hard to put together some scripts to generate these
series of #defines and #undefs on my side when I write the code; a
person dowloading and compiling the code won't even need them.
(Perhaps he will if he wants to change the code seriosly; the tools
would be very portable anyway so this is not an issue.)

The remaining part to design is how to integrate the generation of the
header files so that it's friendly to make and autotools.  And how to
request the desired imports/exports in the C code.  Advice welcome.

What do you think of this?

-- 
Beni Cherniavsky <[email-masked]>

If I don't hack on it, who will?  And if I don't GPL it, what am I?
And if it itches, why not now?  [With apologies to Hillel ;]