I already highly suspect it's doable and not risky at all but I still want to know for sure, so here's my thing...
I have a C++ code that use quite big structs (15-30 fields) as containers, as arguments for the constructor of a class. The thing with those structs is that I need to declare them using the C99 syntax (incompatible with C++ ffs):
FooBar fb = { .foo = 12, .bar = 3.4 };
Because it's unthinkable for me to have a constructor, since some fields can be safely skipped while initializing those structs, while others are not, etc. (they are only and exclusively initialized by "user supplied" data, user is me in the occurence), a bit like if they described a configuration.
Anyways, point made, I'm down to using one .h header that declares the struct using plain C syntax, and one .c file containing the structs I initialize, and THEN I make them accessible in my .cpp files using extern "C". It works well... except I would find very handy to be able to have methods for those structs.
So my question is, is it possible to a declare struct like so
#ifdef __cplusplus
// C++ compatible declarations with methods
struct foobar {
int foo;
float bar;
int method1();
int method2();
void method3();
[etc.]
};
#else
/* C compatible declarations, no methods */
struct foobar {
int foo;
float bar;
};
#endif
This way I could use in C++ some methods bound to the structs (its more elegant, OOP oriented), and I could safely initialize them in my C code using C99's designated initializers.
What I fear is some potentially unknown-by-me issues that could end up making the struct offets different in the C code than in the C++ code. Do those issues exist, or not?
Thanks
I have a C++ code that use **quite big structs (15-30 fields)**<< this could be the real issue. As you care aboutmore elegant, OOP orientedthings, consider scenario where you implicitly solve the problem in the question by properly designing your objects (instead of inventing hacks). SRP is violated here. Remove The God Object, put smaller, maintainable objects instead.