I am writing a small C code for an algorithm. The main target are embedded microcontrollers, however, for testing purposes, a Matlab/Python interface is required.
I am following an embedded programming standard (MISRA-C 2004), which requires the use of C90, and discourage the use of malloc and friends. Therefore, all the arrays in the code have their memory allocated at compile time. If you change the size of the input arrays, you need to recompile the code, which is alright in the microcontroller scenario.
However, when prototyping with Matlab/Python, the size of the input arrays change rather often, and recompiling every time does not seem like an option. In this case, the use of C99 is acceptable, and the size of the arrays should be determined in runtime.
The question is: what options do I have in C to make these two scenarios coexist in the same code, while keeping the code clean?
I must emphasize that my main concern is how to make the code easy to maintain. I have considered using #ifdef to either take the statically allocated array or the dynamically alocated array. But there are too many arrays, I think #ifdef makes the code look ugly.
I’ve thought of a way that you can get away with only one
#ifdef. I would personally just bite the bullet and recompile my code when I need to. The idea of using a different dialect of C for production and test makes me a bit nervous.Anyway, here’s what you can do.
The
ARRAY_SIZEmacro chooses the variableV, if not in the embedded environment; or the fixed sizeS, if in the embedded environment.