Reputation: 2968
So I am making a C program which get's its memory from a static unsigned char[M_SIZE]
array, where M_SIZE
is a macro. What I need to do is to be able to change the value of that macro via a command in make, such that someone could compile the program with a different size of reserved memory depending on arguments passed to make.
My header file example is DataStore.h
#ifndef DATA_STORE_H
#define DATA_STORE_H
#define M_SIZE 50000 // Need this to be configurable via make arguments
unsigned char* DataStore_get_buf(void);
unsigned char* DataStore_get_end(void);
void DataStore_inc_ptr(void);
#endif
My example C file is DataStore.c
#include "DataStore.h"
static unsigned char DataStore_BUFFER[M_SIZE];
static unsigned char* DataStore_PTR = DataStore_BUFFER;
unsigned char* DataStore_get_buf(void)
{
return DataStore_BUFFER;
}
unsigned char* DataStore_get_end(void)
{
return DataStore_BUFFER + M_SIZE;
}
void DataStore_inc_ptr(void)
{
DataStore_PTR++;
}
So Basically, I need a way to change M_SIZE before the program is compiled via some command or some configuration that can be passed into make.
Edit1:
This question is unique because I need a method to not just pass in a configurable macro value, but handle the case in which that value isn't passed in as a command, and a default macro value is used instead.
Upvotes: 1
Views: 1736
Reputation: 753455
If you're sure you want a fixed size set at compile time, modify the header to use:
#ifndef M_SIZE
#define M_SIZE 50000
#endif
Then you can override the macro on the compiler command line:
cc … -DM_SIZE=100000 …
The default is left so that if the compiler option is omitted, the code still compiles sensibly. You could instead decide you want the compilation to fail, but that's typically not such a good choice.
Upvotes: 6
Reputation: 2754
Remove the #define
and pass the value to the compiler's command line like gcc -DM_SIZE=1000
. Or better yet, allocate via malloc
and pass the size as a command line argument, and retrieve it via argv
, which will allow to change the size without recompilation.
Upvotes: 1