Data encapsulation in C

后端 未结 5 1030
醉酒成梦
醉酒成梦 2020-12-24 10:05

I am currently working on an embedded system and I have a component on a board which appears two times. I would like to have one .c and one .h file for the component.

<
5条回答
  •  遥遥无期
    2020-12-24 10:30

    You can:

    1. Make your whole ads1248_options_t an opaque type (as already discussed in other answers)
    2. Make just the adc_values member an opaque type, like:

       // in the header(.h)
      typedef struct adc_values adc_values_t;
      
       // in the code (.c)
      struct adc_values { 
          int32_t *values;
      };
      
    3. Have a static array of array of values "parallel" to your ads1248_options_t and provide functions to access them. Like:

      // in the header (.h)
      int32_t get_adc_value(int id, int value_idx);
      
      // in the code (.c)
      static int32_t values[MAX_ADS][MAX_VALUES];
      // or
      static int32_t *values[MAX_ADS]; // malloc()-ate members somewhere
      
      int32_t get_adc_value(int id, int value_idx) {
          return values[id][value_idx]
      }
      

      If the user doesn't know the index to use, keep an index (id) in your ads1248_options_t.

    4. Instead of a static array, you may provide some other way of allocating the value arrays "in parallel", but, again, need a way to identify which array belongs to which ADC, where its id is the simplest solution.

提交回复
热议问题