Hi Wiwid,
The C preprocessor (using macros) is just doing a syntactic replacement: You CONST_VALUE macro is replaced by "1" whenever you use it.
In most cases, this will be just fine:
#define CONST_VALUE 1
int i = 3 * CONST_VALUE; // Perfect use of the macro
myfunc(CONST_VALUE+2); // Perfect use of the macro
In such cases there is not much need for "storing" your CONST_VALUE in a variable. The compiler will take care of the constant, and will use it appropriately without requiring a specific storing location.
There are some cases, however, where an actual "storage" is required for constants. For instance a signature that should be stored in ROM at a specific location:
at 0x9000 code unsigned long sign = 0xCAFEBABE; // "CAFEBABE" stored at ROM address 0x9000
Other uses are for lookup tables:
// From SHA-1 algorithm
code const long shsTestResults[][ 5 ] =
{ { 0x0164B8A9L, 0x14CD2A5EL, 0x74C4F7FFL, 0x082C4D97L, 0xF1EDF880L },
{ 0xD2516EE1L, 0xACFA5BAFL, 0x33DFC1C4L, 0x71E43844L, 0x9EF134C8L },
{ 0x3232AFFAL, 0x48628A26L, 0x653B5AAAL, 0x44541FD9L, 0x0D690603L } };
This array will be located to ROM space thanks to the code specifier.
Depending on what you need to do in your project, using code-located variables may not be necessary, and relying on a macro such as your CONST_VALUE will be fine.
As a baseline, you should use the "code" directive for variables (including arrays, struct or unions), and only when these variables actually need to be "stored".
Note: The "const" C keyword does NOT make objects ROMable: Instead, it offers a semantic guarantee that no assignment can be done to the variable by the compiler (and ensures that you do not mess up with the variable). Some compilers may consider that a global "const" variable should be in ROM, some others not (as RCSTM8 does), and others can be configured to offer both behaviors. For the sake of code portability you should NOT assume that a const global variable will be in ROM.
Note 2: The C strings are located in ROM on most embedded compilers, and are in not-writeable segments on "PC-targeted" compilers. A good trick if you want to create a portable ROMed variable is then to store it in a string. But this is quite a hack...
I hope this is clear enough, let me know.
Bruno
Bruno Richard, PhD.
RAISONANCE - 17, avenue Jean Kuntzmann - F-38330 Montbonnot St Martin - FRANCE
There are 10 types of people in the world: Those who understand binary, and those who don't.