简体   繁体   中英

Static const structs in C

We are starting a rather big project that involves parts in different languages. We decided to have a certain part translated at compile-time from a JSON to the necessary C structs (and other structures for the rest of the system parts).

The struct is defined in a .h , and the declaration will be like const static struct MCSCommandOptionsMessage mcs_command_message_list[] = and then list of parameters in the format required.

The question is: should the auto generated file with the struct declaration be a .h , or is it better to have a .c just for this struct? Why?

Both would be possible, declaration in .h or in the only one .c file the has access to the struct. If the struct defines something like an Interface and/or you generate several structs if would be good to have them in a .h file. It would define a contract. If several instances of the struct exist you have to put the struct definition in a .h file.

If you would to express Isolation and emphasize that the struct is private matter you can define it in the .c file.

Usually .h files are used as "include" files and are not directly compiled, this is because the code in them shouldn't change to much as they are supposed to define an interface. Just remember that if anything changes in the struct and they are in the .h files then you have to re-compile anything that uses that struct. If the struct was in the .c file it would recompile every time you compile.

Also if the struct is in the .h file you can use it easily in different .c files

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM