C library naming conventions

前端 未结 8 1776
一向
一向 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条回答
  •  说谎
    说谎 (楼主)
    2021-01-31 06:10

    The struct way that Ken mentions would look something like this:

    struct MyCoolApi
    {
      int (*add)(int x, int y);
    };
    
    MyCoolApi * my_cool_api_initialize(void);
    

    Then clients would do:

    #include 
    #include 
    
    #include "mycoolapi.h"
    
    int main(void)
    {
      struct MyCoolApi *api;
    
      if((api = my_cool_api_initialize()) != NULL)
      {
        int sum = api->add(3, 39);
    
        printf("The cool API considers 3 + 39 to be %d\n", sum);
      }
      return EXIT_SUCCESS;
    }
    

    This still has "namespace-issues"; the struct name (called the "struct tag") needs to be unique, and you can't declare nested structs that are useful by themselves. It works well for collecting functions though, and is a technique you see quite often in C.

    UPDATE: Here's how the implementation side could look, this was requested in a comment:

    #include "mycoolapi.h"
    
    /* Note: This does **not** pollute the global namespace,
     * since the function is static.
    */
    static int add(int x, int y)
    {
      return x + y;
    }
    
    struct MyCoolApi * my_cool_api_initialize(void)
    {
      /* Since we don't need to do anything at initialize,
       * just keep a const struct ready and return it.
      */
      static const struct MyCoolApi the_api = {
        add
      };
    
      return &the_api;
    }
    

提交回复
热议问题