Why doesn't ANSI C have namespaces?

前端 未结 9 1663
無奈伤痛
無奈伤痛 2020-11-27 10:02

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?

9条回答
  •  旧巷少年郎
    2020-11-27 10:37

    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.

提交回复
热议问题