I have a an application header file in c where I mention the variable.
#VAR_X "testData"
User can change this variable but I want to restrict it's length to maximum of 50.If user tries to make it more than 50 there should be an error on building the code.
I have done like this in the application.h:
#define __IS_MORE if((strlen(VAR_X) - 50) > 0) 1:0;
and in application.c at the top .
#define application.h
#if defined(__IS_MORE)
#error "Size is more than the maximum size"
#endif
But no matter what I put in the VAR I always get the #error directive "Size is more than the maximum size"
What wrong I am doing?
At compile time, you can do this by using a technique called as static assert. you can find the details here. Assuming a STATIC_ASSERT macro is defined as explained in the link, you can do the following to check if VAR_X exceeds the length (Here I assume that VAR_X is a macro as in #define VAR_X "...")
STATIC_ASSERT(sizeof(VAR_X) <= 50, "Size of VAR_X is more than the maximum size");
Some example code
#define STATIC_ASSERT(COND,MSG) typedef char static_assertion_##MSG[(COND)?1:-1]
#define VAR_X "012345678912912"
STATIC_ASSERT(sizeof(VAR_X) <= 50, Size_of_VAR_X_is_more_than_the_maximum_size);
int main()
{
return 0;
}