Best practice on writing constant parameters for embedded systems
c, c-preprocessor, constants, embedded
Solution
Always consider readability and memory constraints. Also, macros are simply copy/paste operations that occur before compilation. With that being said I like to do the following:
- I define all variables that are constant as being `static const` if they are to be used in one c file (e.g. not globally accessible across multiple files). Anything defined as `const` shall be placed in ROM when at file scope. Obviously you cannot change these variables after they're initialized.
- I define all constant values using `#define`.
- I use `enum`erations where it adds to readability. Any place where you have a fixed range of values I prefer enumerations to explicitly state the intent.
Try to approach the project with an object oriented perspective (even though c isn't OO). Hide private functions (don't create a prototype in the header), do not use globals if you can avoid it, mark variables that should only reside in one c module (file) as `static`, etc.
Problem
This is a case of "static const” vs “#define” in C" for embedded systems. On large/mid projects with "passed-down" code and modules, what is the best practice on writing constant parameters for your include files, modules, etc? In a code "passed-down" where you don't know if the names you're choosing are defined in some other included file or might be called with extern or as macros in some other file that might include your file. Having these 3 options: - `static const int char_height = 12;` - `#define CHAR_HEIGHT 12` - `enum { char_height = 12 };` which one would be better (on an embedded system with unknown memory constraints)? The original code uses mainly `#define`'s for this, but these kind of constants are haphazardly implemented in several ways (and at different locations even in the same files) since it seems several people developed this demo software for a certain device. Specifically, this is a demo code, showing off every hardware and SDK feature of a certain device. Most of the data I'm thinking about is the kind used to configure the environment: screen dimensions, charset characteristics, something to improve the readability of the code. Not on the automatic configuration a compiler and pre-processor could do. But since there's a lot of code in there and I'm afraid of global name conflicts, I'm reluctant to use #define's Currently, I'm considering that it would be better to rewrite the project from scratch and re-implement most of the already written functions to get their constants from just one c file or reorganize the constants' implementation to just one style. But: - This is a one person project (so it would take a lot of time to re-implement everything) - The already implemented code works and it has been revised several times. (If it's not broken...)