I have the following code that produces a compile error. It is for a command parser for a STM32 micro-controller written in C++. Basically I have a CMD_DEF_ST
struct with a string and a function pointer to handle that string. I added a further pointer to another CMD_DEF_ST
array in the struct, to be able to handle command parameters. I cannot get the initialisation right unfortunately. I do not want to initialize it at runtime, as it all has to go into const FLASH memory.
#include <stdio.h>
// **************************
// define command structure
// **************************
// struct forward declaration
typedef struct cmd_def_st CMD_DEF_ST;
// typedef for command handler function
typedef void (*CMD_FUNC_HANDLER)(const CMD_DEF_ST* cmddef);
struct cmd_def_st
{
const char* cmdstr; // command string
const CMD_FUNC_HANDLER func; // pointer to handler
const CMD_DEF_ST* params; // pointer to sub parameters
};
// **************************
// declare some commands
// **************************
const CMD_DEF_ST cmd = {"swrst" , [] (const CMD_DEF_ST* cmd) { printf("swrst\n"); },
NULL};
// **************************
// produces:
// error: braces around scalar initializer for type 'const CMD_DEF_ST*
// {aka const cmd_def_st*}'
// **************************
const CMD_DEF_ST cmd2 = { "echo" , [] (const CMD_DEF_ST* cmd) { printf("Error\n"); },
{
{"on" , [] (const CMD_DEF_ST* cmd) { printf("Echo on\n"); }, NULL },
{"off" , [] (const CMD_DEF_ST* cmd) { printf("Echo off\n"); }, NULL },
NULL
}
};
int main()
{
cmd.func(&cmd); // prints "swrst"
return 0;
}
I had a look here gcc warning: braces around scalar initializer and here initializing array of pointers to structs. It gave me a few ideas to try, but I could not quite figure out how to make it work for my own code.
I tried changing the struct definition to:
struct cmd_def_st
{
const char* cmdstr; // command string
const CMD_FUNC_HANDLER func; // pointer to handler
const CMD_DEF_ST** params; // pointer to sub parameters
};
with
// **************************
// produces:
// error: taking address of temporary [-fpermissive]|
// error: taking address of temporary [-fpermissive]|
// error: taking address of temporary array|
// **************************
const CMD_DEF_ST cmd2 = { "echo" , [] (const CMD_DEF_ST* cmd) { printf("Error\n"); },
(const CMD_DEF_ST* []){
&(const CMD_DEF_ST){"on" , [] (const CMD_DEF_ST* cmd) { printf("Echo on\n"); }, NULL },
&(const CMD_DEF_ST){"off" , [] (const CMD_DEF_ST* cmd) { printf("Echo off\n"); }, NULL },
NULL
}
};
but I still got a compile error.
Can someone tell me what is the correct way to initialize cmd2
, or does someone know of a good way to do this?