The Problem
I am doing some firmware coding and have a lot of bitmasks to manage. Until now, I have been repeating the same block for each field I want to mask as follows:
#define LinkStateMask 0x1
#define LinkStateShift 8
#define LinkState(x) (((x) >> LinkStateShift) & LinkStateMask)
Note that the fields are quite often multi-bit fields so the mask is not always guaranteed to be 0x1
. The final macro can be used in the code quite readably and this is something I quite like:
if( LinkState(temp) == 0 ) {
// Link is down, return error
return -ENODEV;
}
The Question
Is there any way to have the C preprocessor generate these macros for me? I know that the preprocessor only works in a single pass so a macro cannot directly define another but hopefully there is another way.
Ideally, I would like to write something similar to the following and use the same C code as my second listing above:
BIT_FIELD(LinkState, 8, 0x1) // BIT_FIELD(name, lsb, mask)
The key for me is keeping the symbolically named, function-style usage in the main C file without having to write the whole BIT_FIELD(...)
invocation each time I need to generate a mask (some of these fields are used extensively, leading to a maintenance nightmare).
One final restriction: the fields I need are sparsely scattered across hundreds of registers. If at all possible, I would really like to avoid having to define a struct
for each as I usually only need one or two fields out of each.