Why doesn’t ANSI C have namespaces?

For completeness there are several ways to achieve the “benefits” you might get from namespaces, in C.

One of my favorite methods is using a structure to house a bunch of method pointers which are the interface to your library/etc..

You then use an extern instance of this structure which you initialize inside your library pointing to all your functions. This allows you to keep your names simple in your library without stepping on the clients namespace (other than the extern variable at global scope, 1 variable vs possibly hundreds of methods..)

There is some additional maintenance involved but I feel that it is minimal.

Here is an example:

/* interface.h */

struct library {
    const int some_value;
    void (*method1)(void);
    void (*method2)(int);
    /* ... */
};

extern const struct library Library;
/* interface.h */

/* interface.c */
#include "interface.h"

void method1(void)
{
   ...
}
void method2(int arg)
{
   ...
}

const struct library Library = {
    .method1 = method1,
    .method2 = method2,
    .some_value = 36
};
/* end interface.c */

/* client code */
#include "interface.h"

int main(void)
{
    Library.method1();
    Library.method2(5);
    printf("%d\n", Library.some_value);
    return 0;
}
/* end */

The use of . syntax creates a strong association over the classic Library_function() Library_some_value method. There are some limitations however, for one you can’t use macros as functions.

Leave a Comment