Solved: “designator outside aggregate initializer”

You might come across this error “C99 designator outside aggregate initializer” when you are compiling projects based on C code, but the compiler is expecting C++ code. For example, we got this issue when trying to compile a custom C Arduino library file for ESP32:

c99 designator outside aggregate initializer
"C99 designator outside aggregate initializer" error within Arduino IDE for ESP32

Here is how we solved it.

The structure that caused this error

static pcba_device_profile sdp = 
{
    .api_key =  "GkPv9WW3JQwiCxt",
	.mac =      "74:FF:AA:FF:AA:CC",
    .type =     "sensor",
    .mfg =      "PCB Artists",
    .model =    "Test Sensor v1",
    .serial =   "PCBATS-599916"
};

Solution #1

The first thing to do would be to force the compiler to treat your code like C code, even if it is found within a Cpp file. This ensures that the compiler does not assume that the C code variables are subject to being treated as C++ variables. Here is how you can do this:

#ifdef __cplusplus
extern "C"
{
#endif

    // C code goes here
    
#ifdef __cplusplus
}
#endif

If this does not work, you will need to change the way default strings are assigned to a structure as shown in solution #2 below.

Solution #2

#ifdef __cplusplus
    extern "C"
    {
#endif

static pcba_device_profile sdp = 
{
    {.api_key =  "GkPv9WW3JQwiCxt"},
	{.mac =      "74:FF:AA:FF:AA:CC"},
    {.type =     "sensor"},
    {.mfg =      "PCB Artists"},
    {.model =    "Test Sensor v1"},
    {.serial =   "PCBATS-599916"}
};
    
#ifdef __cplusplus
    }
#endif

Using braces around the assignment seemed to work for us in some cases. However, if even this fails to get rid of the “designator outside aggregate initializer” error, you can try solution #3.

We don’t like this because it can be very unreadable when large or nested structures are initialized like this. But if you have no choice or your structure is very simple, say SSID and PASSWORD for a WiFi network, you can manage with the following solution.

Solution #3

#ifdef __cplusplus
    extern "C"
    {
#endif

static pcba_device_profile sdp = 
{
    "GkPv9WW3JQwiCxt",     // api_key
	"74:FF:AA:FF:AA:CC",   // mac
    "sensor",              // type
    "PCB Artists",         // mfg
    "Test Sensor v1",      // model
    "PCBATS-599916"        // serial
};
    
#ifdef __cplusplus
    }
#endif

We hope one of the above solutions worked for you!
Please leave us a comment below if you have something that could help others!

Change Log
  • Initial Release: 17 April 2021
References

You may also like

Leave a Comment

17 − twelve =