Why doesn't ANSI C have namespaces?

前端 未结 9 1659
無奈伤痛
無奈伤痛 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:24

    C doesn't support namespaces like C++. The implementation of C++ namespaces mangle the names. The approach outlined below allows you to get the benefit of namespaces in C++ while having names that are not mangled. I realize that the nature of the question is why doesn't C support namespaces (and a trivial answer would be that it doesn't because it wasn't implemented :)). I just thought that it might help someone to see how I've implemented the functionality of templates and namespaces.

    I wrote up a tutorial on how to get the advantage of namespaces and/or templates using C.

    Namespaces and templates in C

    Namespaces and templates in C (using Linked Lists)

    For the basic namespace, one can simply prefix the namespace name as a convention.

    namespace MY_OBJECT {
      struct HANDLE;
      HANDLE *init();
      void destroy(HANDLE * & h);
    
      void do_something(HANDLE *h, ... );
    }
    

    can be written as

    struct MY_OBJECT_HANDLE;
    struct MY_OBJECT_HANDLE *my_object_init();
    void my_object_destroy( MY_OBJECT_HANDLE * & h );
    
    void my_object_do_something(MY_OBJECT_HANDLE *h, ... );
    

    A second approach that I have needed that uses the concept of namespacing and templates is to use the macro concatenation and include. For example, I can create a

    template T multiply( T x, T y ) { return x*y }
    

    using template files as follows

    multiply-template.h

    _multiply_type_ _multiply_(multiply)( _multiply_type_ x, _multiply_type_ y);
    

    multiply-template.c

    _multiply_type_ _multiply_(multiply)( _multiply_type_ x, _multiply_type_ y) {
      return x*y;
    }
    

    We can now define int_multiply as follows. In this example, I'll create a int_multiply.h/.c file.

    int_multiply.h

    #ifndef _INT_MULTIPLY_H
    #define _INT_MULTIPLY_H
    
    #ifdef _multiply_
    #undef _multiply_
    #endif
    #define _multiply_(NAME) int ## _ ## NAME 
    
    #ifdef _multiply_type_
    #undef _multiply_type_
    #endif
    #define _multiply_type_ int 
    
    #include "multiply-template.h" 
    #endif
    

    int_multiply.c

    #include "int_multiply.h"
    #include "multiply-template.c"
    

    At the end of all of this, you will have a function and header file for.

    int int_multiply( int x, int y ) { return x * y }
    

    I created a much more detailed tutorial on the links provided which show how it works with linked lists. Hopefully this helps someone!

提交回复
热议问题