C library naming conventions

前端 未结 8 1871
一向
一向 2021-01-31 05:50

Introduction

Hello folks, I recently learned to program in C! (This was a huge step for me, since C++ was the first language, I had contact with and scared me off for

8条回答
  •  萌比男神i
    2021-01-31 06:16

    As a library user, you can easily define your own shortened namespaces via the preprocessor; the result will look a bit strange, but it works:

    #define ns(NAME) my_cool_namespace_ ## NAME
    

    makes it possible to write

    ns(foo)(42)
    

    instead of

    my_cool_namespace_foo(42)
    

    As a library author, you can provide shortened names as desribed here.

    If you follow unwinds's advice and create an API structure, you should make the function pointers compile-time constants to make inlinig possible, ie in your .h file, use the follwoing code:

    // canonical name
    extern int my_cool_api_add(int x, int y);
    
    // API structure
    struct my_cool_api
    {
        int (*add)(int x, int y);
    };
    
    typedef const struct my_cool_api *MyCoolApi;
    
    // define in header to make inlining possible
    static MyCoolApi my_cool_api_initialize(void)
    {
        static const struct my_cool_api the_api = { my_cool_api_add };
        return &the_api;
    }
    

提交回复
热议问题