Is it possible to have C macros with any sort of state? In this particular case, an integer value.
I want to be able to allocate some memory from statically allocated buffer, since I am in an embedded environment. Say I have a struct like this and a buffer:
double buffer[1000];
typedef struct {
int rows;
int cols;
double* data;
} matrix;
I would like to have macro that can generate a matrix and allocate the relevant memory from the buffer in question. However, I cannot seem to think of a way to keep an internal counter of where in the buffer we should be at the moment. Ideally, the macro would be something like:
#define alloc_matrix(_rows, _cols) {.rows = _rows, .cols = _cols, .data = &buffer[PTR]}
where PTR is compile time constant that is constantly changing (increasing by rows * cols) for every usage of alloc_matrix. This would allow me check if everything fits the buffer during compile time using something like _Static_assert, instead of checking everything during runtime.
Is this possible with the C preprocessor?
I have tried using the C preprocessor but can't seems to find a way to store a state in the macros.
It is possible if you think outside the box. Why must you be allocating chunks pointing into a pre-allocated array?
Instead, consider making a struct containing nothing but
doublearray members. Such a struct wouldn't have any padding or alignment problems. It will grow in size as you add more members, all at compile-time.Rolling out the infamous but ridiculously flexible "X macros", we can declare all our matrices/arrays in an abstract list:
Now create a struct type based on this:
This expands to:
An instance of this struct will take up exactly that amount, no more, no less. We need not pre-allocate an arbitrary chunk and try to assign pointers into it.
This gives:
(1803 * 8 = 14424, so there was no padding as predicted)
You may access individual matrices/arrays like you would any struct member:
Wanna know the row or column size of
data42? Make a corresponding enum for look-up:And so on. This is all 100% pure compile-time calculations.