I'm running C on an embedded system and I want to make sure that the value of a certain #define is equal to a specific value. If not, I want the compiler to fail and not proceed.
My code currently looks like this:
typedef uint32_t TickType_t; //I can NOT change/modify this typedef
#define configTICK_RATE_HZ ( ( TickType_t ) 1000 ) //I can NOT change/modify this macro, it's autogenerated
I'm then trying to do the following in my code:
#if(1000 != configTICK_RATE_HZ)
#error "configTICK_RATE_HZ is not 1000Hz!"
#endif
I run into an error during the build because the #if doesn't like seeing that typecast (compilers don't know typedefs). I found a stackoverflow discussion about how to strip/remove the typecast (link) with a very creative answer but it's not quite working for me yet because I think I need to remove the outmost parenthesis from the original macro first before using that creative solution.
Asked another way, I want the preprocessor output of this:
#if(1000 != configTICK_RATE_HZ )
To look like this:
#if(1000 != 1000)
And not like this:
#if(1000 != ( ( TickType_t ) 1000 ) )
I don't mind intermediate macros if needed, but I can not change the original "configTICK_RATE_HZ" definition or the typedef of TickType_t
Here's some minimal reproducible code (a similar problem that covers the same issue that I'm running into). The code below fails because it doesn't like the typecast or the outmost parenthesis in that macro.
#include <stdio.h>
#define FREQ_HZ ((int)10) //Can not modify this definition
#if( 10 != FREQ_HZ )
#error "Bad frequency value"
#endif
int main(void)
{
printf("Hello world\n");
}
You can't use the preprocessor for this, but you can use a static assertion.
The static_assert
declaration allows for a constant expression to be checked at compile time and generate an error with the given text if the condition is false.
static_assert(1000 == configTICK_RATE_HZ, "configTICK_RATE_HZ is not 1000Hz!");