Search code examples
cnamespacesansi-c

Why doesn't ANSI C have namespaces?


Having namespaces seems like no-brainer for most languages. But as far as I can tell, ANSI C doesn't support it. Why not? Any plans to include it in a future standard?


Solution

  • C does have namespaces. One for structure tags, and one for other types. Consider the following definition:

    struct foo
    {
        int a;
    };
    
    typedef struct bar
    {
        int a;
    } foo;
    

    The first one has tag foo, and the later is made into type foo with a typedef. Still no name-clashing happens. This is because structure tags and types (built-in types and typedef'ed types) live in separate namespaces.

    What C doesn't allow is to create new namespace by will. C was standardized before this was deemed important in a language, and adding namespaces would also threaten backwards-compatibility, because it requires name mangling to work right. I think this can be attributed due to technicalities, not philosophy.

    EDIT: JeremyP fortunately corrected me and mentioned the namespaces I missed. There are namespaces for labels and for struct/union members as well.