Search code examples
c

switching C compiler causes: Error Initializer cannot be specified for a flexible array member


I am trying to convert our code from one IDE to be used in a different one. The current one uses gcc which allows for this structure to be initialized from a variable array. The new tool does not use gcc gives me an error "Initializer cannot be specified for a flexible array member". So can someone help me understand how to set this up? Should I set up a blank array of variable size and then somewhere assign the #define array as seen below?

Here would be an example of the code…(this is current implementation current IDE)

In one header file that is Build switchable so we can build this on different hardware platforms we have the following #define

#define GPIOS  \ 
          /*     BANK, PIN, SPD,  MODE,…  */
      GPIOINIT(   A,   0,   2,   AIN,  …) \
      GPIOINIT(   A,   1,   2,   AIN,  …) \
      GPIOINTINIT(A,   2,   2,   AIN,  …) \
      .
      .
      .

Then in a different header file that is used in all builds we have

  PLATFORM_CONFIG_T g_platformConfig = {
          .name = {PLATFORM_NAME},

          (bunch of other stuff),

         .allGpios = {
                     GPIOS /* here I get the error */
         },
   };

So I am thinking I can make the error line a variable array and assign to it later in some other way? The problem is the actual array "GPIO" is of different types and pin orders on different designs are different.


Solution

  • Initializing flexible array members with an aggregate is a gcc extension. The good news is that since you are allocating the g_platformConfig statically, you do not need that member to be a flexible array: you can go for a fixed-size array instead.

    It is very likely that somewhere in your code you have a definition of the constant that says how many items there are in the GPIOS array (otherwise, you'd need to rely on a "sentinel" value of sorts, similar to null terminator of C strings, to know where legitimate GPIOS values end). If you have that constant already, modify the definition of allGpios to be

    gpoinit_t allGpios[GPIO_COUNT]; // regular array
    

    instead of

    gpoinit_t allGpios[]; // flexible array
    

    With this change in place, your code should compile correctly.

    If you do not have a GPIO_COUNT constant, consider either adding one, or introducing a MAX_GPIO value limiting the number of items in allGpios. Either way, converting the array to a non-flexible one will fix the error.