Compile-time assertion fails without GCC optimization - c

I have following compile-time assertion which fails if I compile without -O[1-3] flags.
#ifndef __compiletime_error
#define __compiletime_error(message)
#endif
#ifndef __compiletime_error_fallback
#define __compiletime_error_fallback(condition) do { } while (0)
#endif
#define __compiletime_assert(condition, msg, prefix, suffix) \
do { \
int __cond = !(condition); \
extern void prefix ## suffix(void) __compiletime_error(msg); \
if (__cond) \
prefix ## suffix(); \
__compiletime_error_fallback(__cond); \
} while (0)
#define _compiletime_assert(condition, msg, prefix, suffix) \
__compiletime_assert(condition, msg, prefix, suffix)
#define compiletime_assert(condition, msg) \
_compiletime_assert(condition, msg, __compiletime_assert_, __LINE__)
#endif
This would combine with the following macro which is located in another (gcc-4 specific) file:
#define __compiletime_error(message) __attribute__((error(message)))
the issue comes from this line in the code:
extern void prefix ## suffix(void) __compiletime_error(msg); \
It seems GCC does not understand extern in the macro without -O[1-3] flag. I am not sure how should I declare __compiletime_error before it actually gets called in this macro. If I remove this line, I get famous warning of Implicit declaration of a function

Your compiletime_assert framework is relying on the optimizer performing dead code elimination to remove the call to prefix ## suffix. This is highly fragile and is in no way guaranteed to work.
Instead, try using one of the solutions from Ways to ASSERT expressions at build time in C - or, since you're using a modern compiler, just use C11 _Static_assert.

Related

X-macros: how to make the list of variables compile-time configurable?

I have code similar to
#define LIST_OF_VARIABLES \
X(value1) \
X(value2) \
X(value3)
as explained in https://en.wikipedia.org/wiki/X_Macro
Now I have the need to make the LIST_OF_VARIABLES configurable at compile time
So it could effectively be e.g.
#define LIST_OF_VARIABLES \
X(default_value1) \
X(cust_value2) \
X(default_value3)
or e.g.
#define LIST_OF_VARIABLES \
X(default_value1) \
X(default_value2) \
X(cust_value3)
depending on some macros previously defined. The LIST_OF_VARIABLES is long and the customizations are relatively small. I would not like to copy the long list for each customization, because that will cause maintenance issues (the DRY principle https://en.wikipedia.org/wiki/Don%27t_repeat_yourself). As a matter of fact the LIST_OF_VARIABLES should be in one file and the
customizations elsewhere (either another file or just -D options in the Makefile)
In pseudo-code I was thinking of something like
#define X(arg) \
#ifdef CUST_##arg \
Y(CUST_##arg) \
#else \
Y(DEFAULT_##arg) \
#endif
And then use the X-macros under the name Y.
But of course that does not work, because a macro cannot contain preprocessor
directives.
What would be a way to achieve this? C is a must (no templates or Boost
macros), gcc specific solutions are acceptable.
I think that what you have to do is along the lines of:
#ifdef USE_DEFAULT_VALUE1
#define X_DEFAULT_VALUE1 X(default_value1)
#else
#define X_DEFAULT_VALUE1 /* omitted */
#endif
#ifdef USE_DEFAULT_VALUE2
#define X_DEFAULT_VALUE2 X(default_value2)
#else
#define X_DEFAULT_VALUE2 /* omitted */
#endif
#ifdef USE_DEFAULT_VALUE3
#define X_DEFAULT_VALUE3 X(default_value3)
#else
#define X_DEFAULT_VALUE3 /* omitted */
#endif
#ifdef USE_CUST_VALUE1
#define X_CUST_VALUE1 X(cust_value1)
#else
#define X_CUST_VALUE1 /* omitted */
#endif
#ifdef USE_CUST_VALUE2
#define X_CUST_VALUE2 X(cust_value2)
#else
#define X_CUST_VALUE2 /* omitted */
#endif
#define LIST_OF_VARIABLES \
X_DEFAULT_VALUE1 \
X_DEFAULT_VALUE2 \
X_DEFAULT_VALUE3 \
X_CUST_VALUE1 \
X_CUST_VALUE2 \
You then need to define USE_DEFAULT_VALUE1 etc as required for the specific configuration you are after.
As long as you always need the items in the same order, this is sufficient. If you need them in different orders, then you conditionally define LIST_OF_VARIABLES in the different sequences.
Answering myself.
With help of the comments I came up with a solution that works and meets most
requirements I had mentioned
With the "main code"
$cat main.c
#ifndef VALUE1
#define VALUE1 value1
#endif
#ifndef VALUE2
#define VALUE2 value2
#endif
#ifndef VALUE3
#define VALUE3 value3
#endif
#define LIST_OF_VARIABLES \
X(VALUE1) \
X(VALUE2) \
X(VALUE3)
and a customization file like
$cat cust1
-DVALUE2=value2cust
the code can be compiled using (GNUmake pseudo syntax)
$(CC) $(CFLAGS) $(shell cat cust1) main.c
Actually having the extra indirection with every value defined on a single
line is good, because it allows commenting the values. That would not have
been possible with the continuation lines in the single LIST_OF_VARIABLES macro.
Edit: Not true. A COMMENT(foo) macro expanding to nothing would have solved that issue, too. (Credit: Got the idea from the answer posted by #Jonathan Leffer.)
However the approach does not yet meet the following requirements I hadn't mentioned
no ugly boilerplate code (all these #ifndef lines are not really nice)
customization should also make it possible to drop default values from the
list altogether or add completely new values (yes, this could probably be
done with some ugly dummy code already now)
So not really satisfied yet with my own answer. Need to think about the
approach from the Dr. Dobbs article a bit more, maybe that can be used.
Open for better answers.
Given further context, it appears you want to be able to cherry pick individual values from your list at compile time. I think you might be interested in a preprocessor switch, which can accomplish what you're using preprocessor conditionals for with a lot less boilerplate.
Generic preprocessor switch
Here's a brief framework:
#define GLUEI(A,B) A##B
#define GLUE(A,B) GLUEI(A,B)
#define SECONDI(A,B,...) B
#define SECOND(...) SECONDI(__VA_ARGS__,,)
#define SWITCH(NAME_, PATTERN_, DEFAULT_) SECOND(GLUE(NAME_,PATTERN_), DEFAULT_)
SWITCH macro usage
Invoke SWITCH(MY_PREFIX_,SPECIFIC_IDENTIFIER,DEFAULT_VALUE) to expand everything that is not a matching pattern to DEFAULT_VALUE. Things that are a matching pattern can expand to whatever you map them to.
To create a matching pattern, define an object like macro called MY_PREFIX_SPECIFIC_IDENTIFIER, whose replacement list consists of a single comma followed by the value you want the SWITCH to expand to in this case.
The magic here is simply that SWITCH builds a hidden token, giving it a chance to expand (well, in this implementation SECOND's indirection is also significant), and inject a new second argument to SECOND if it's defined. Nominally this new token isn't defined; in such cases, it simply becomes the first argument to SECOND, which just discards it, never to be seen again.
For example, given the above macros:
#define CONTRACT_IDENTIFIER_FOR_DEFAULT , overridden_id_for_default
#define CONTRACT_IDENTIFIER_FOR_SIGNED , overridden_id_for_signed
SWITCH(CONTRACT_IDENTIFIER_FOR_, DRAFT , draft )
SWITCH(CONTRACT_IDENTIFIER_FOR_, DRAWN , drawn )
SWITCH(CONTRACT_IDENTIFIER_FOR_, PROOFED , proofed )
SWITCH(CONTRACT_IDENTIFIER_FOR_, DELIVERED , delivered )
SWITCH(CONTRACT_IDENTIFIER_FOR_, SIGNED , signed )
SWITCH(CONTRACT_IDENTIFIER_FOR_, FULFILLED , fulfilled )
SWITCH(CONTRACT_IDENTIFIER_FOR_, DEFAULT , default )
...will expand to:
draft
drawn
proofed
delivered
overridden_id_for_signed
fulfilled
overridden_id_for_default
Decorated X Macros
Assuming you wish to give your values names, and simply replace cherry picked values from the command line, you can make use of SWITCH to do something like this:
#define VARVALUE(N_,V_) SWITCH(VALUE_FOR_, N_, V_)
#define LIST_OF_VARIABLES \
X(VARVALUE(value1, default_value1)) \
X(VARVALUE(value2, default_value2)) \
X(VARVALUE(value3, default_value3))
The VARVALUE macros will be applied first in this form. To override a specific value, you can define your pattern matcher using either a #define:
#define VALUE_FOR_value2 , custom_value2
...or on the command line/makefile:
CFLAGS += -DVALUE_FOR_value2=,custom_value2
Disable/insertion using switch macro
To support disabling individual items safely, nest two switches and add an EAT macro to catch the entry:
#define EAT(...)
#define SELECT_ITEM_MACRO_FOR_STATE_ON , X
#define X_IF_ENABLED(N_, V_) \
SWITCH(SELECT_ITEM_MACRO_FOR_STATE_, SWITCH(ENABLE_VALUE_, N_, ON), EAT) \
(SWITCH(VALUE_FOR_, N_, V_))
#define LIST_OF_VARIABLES \
X_IF_ENABLED(value1, default_value1) \
X_IF_ENABLED(value2, default_value2) \
X_IF_ENABLED(value3, default_value3)
Just as before, individual macros can be overridden using VALUE_FOR_valuex pattern macros, but this also allows disabling items using ENABLE_VALUE_valuex macros, which can be set to anything but ,ON to disable that item.
Similarly, one way to add support for inserting values is to flip the idea:
#define ADD_ITEM_MACRO_FOR_STATE_EAT , EAT
#define X_IF_ADDED(N_) \
SWITCH(ADD_ITEM_MACRO_FOR_STATE_, SWITCH(VALUE_FOR_, N_, EAT), X) \
(SECOND(GLUE(VALUE_FOR_,N_)))
#define LIST_OF_VARIABLES \
X_IF_ENABLED(value1, default_value1) \
X_IF_ENABLED(value2, default_value2) \
X_IF_ENABLED(value3, default_value3) \
X_IF_ADDED(value4) \
X_IF_ADDED(value5) \
X_IF_ADDED(value6)
...this allows you to define VALUE_FOR_value4 as a a pattern macro, but by default will expand to nothing.
Summary
The framework supporting setting, removing, or inserting values winds up being:
#define GLUEI(A,B) A##B
#define GLUE(A,B) GLUEI(A,B)
#define SECONDI(A,B,...) B
#define SECOND(...) SECONDI(__VA_ARGS__,,)
#define SWITCH(NAME_, PATTERN_, DEFAULT_) SECOND(GLUE(NAME_,PATTERN_), DEFAULT_)
#define EAT(...)
#define SELECT_ITEM_MACRO_FOR_STATE_ON , X
#define X_IF_ENABLED(N_, V_) \
SWITCH(SELECT_ITEM_MACRO_FOR_STATE_, SWITCH(ENABLE_VALUE_, N_, ON), EAT) \
(SWITCH(VALUE_FOR_, N_, V_))
#define ADD_ITEM_MACRO_FOR_STATE_EAT , EAT
#define X_IF_ADDED(N_) \
SWITCH(ADD_ITEM_MACRO_FOR_STATE_, SWITCH(VALUE_FOR_, N_, EAT), X) \
(SECOND(GLUE(VALUE_FOR_,N_)))
Given this framework, your list macro would be comprised of a series of X(value), X_IF_ENABLED(name,default_value), and/or X_IF_ADDED(name) values, where:
X(value) can be used to always insert a call to the X macro with value
X_IF_ENABLED(name,default_value) will call X with default_value, allowing you to override the default based on name.
X_IF_ADDED(name) will provide an "empty slot" with name, which will do nothing unless you override that slot.
Overriding slots is done by defining VALUE_FOR_name to expand to ,replacement. Disabling enabled slots is done by defining ENABLE_VALUE_name to expand to ,OFF.
Demo showing change, removal, addition using command line

Code section as macro parameter

For a debug purpose I defined the following macro
#define SECTION_TIME(out, s) GPIO_SetOut(out); \
s \
GPIO_ClrOut(out);
usage:
SECTION_TIME(GPIO_fooOut,
foo();
bar();
foo=bar^foo;....;....;
)
Goal: needed to mesure time of some code.
Sometimes this macro do not compile. Did I miss understand somthing?
PS: I also tried surrounding my code with {}
error: macro "SECTION_TIME" passed 6 arguments, but takes just 2
When code walks like a duck and talks like a duck, it better fully behave exactly like a duck. What I mean by that is that SECTION_TIME(GPIO_fooOut, ...) (sort of) looks like one statement while in reality it maps to 3 or more statements. This is bad, and you should strive to truely make it one statement.
This is actually not difficult, and the common idiom used for this is to wrap the macro content in do { ... } while (0) without a trailing semicolon (so that the trailing semicolon is supplied to the end of the macro invocation).
So you should at least change your macro to something like
#define SECTION_TIME(out, s) \
do { \
GPIO_SetOut(out); \
s; \
GPIO_ClrOut(out); \
} while (0)
Also notice here that you should put the terminating semicolon for s in the macro and not the argument. So the macro should be invoked like
SECTION_TIME(GPIO_fooOut,
foo();
bar();
foo=bar^foo;....;....
);
Depending on use cases, the suggestion to use SETION_TIME_BEGIN and SECTION_TIME_END might be a better solution.
Solved using variadic macro
#define BOARD_SECTION_TIME(out, ...) do { \
GPIO_SetOut(out); \
__VA_ARGS__ \
GPIO_ClrOut(out); \
} while(0)
I also use the way of __VA_ARGS__ but I also make some curry-like syntax by defining a second macro, which name is in the first:
#define SECTION_TIME(out) \
do { \
/* remember to save the value, so that the same output is always cleared and can be used in the second one */ \
decltype(out) _o = out; \
GPIO_SetOut(_o); \
SECTION_TIME_BLOCK1
#define SECTION_TIME_BLOCK1(...) \
{__VA_ARGS__}; \
GPIO_ClrOut(_o); \
} while(0);
And it can be used like this:
SECTION_TIME(GPIO_fooOut) (
foo();
bar();
foo=bar^foo;
//....;....;
);
You see that the out input-parameter is a separate tuple and that the syntax is similar to the syntax of if for example, only the brackets are different. And if you want to define only one macro, you say that the code-parameter(s) should be in a tuple:
// this macro is only a help to remove the brackets and can be used in multiple definitions
#define PP_REMOVE_BRACKETS(...) __VA_ARGS__
/**
* \param code a tuple containing the code you want to run
**/
#define SECTION_TIME(out, code) \
do { \
/* remember to save the value, so that the same output is always cleared */ \
decltype(out) _o = out; \
GPIO_SetOut(_o); \
{PP_REMOVE_BRACKETS code}; \
GPIO_ClrOut(_o); \
} while(0);
This can be used like this:
SECTION_TIME(GPIO_fooOut, (
foo();
bar();
foo=bar^foo;
//....;....;
));

Alternative (args...) token for the CL compiler

What is the alternative token (args...) for the CL compiler?
#define DECLARE_C_ARRAY(__type, __name, __page, __args...) \
enum { __name##_page_size = __page }; \
typedef __type __name##_element_t; \
typedef C_ARRAY_SIZE_TYPE __name##_count_t; \
typedef struct __name##_t {\
volatile __name##_count_t count;\
volatile __name##_count_t size;\
__name##_element_t * e;\
__args ;\
} __name##_t, *__name##_p;
Example for the GCC compiler
Take a look to Variadic macros
Variadic macros are a new feature in C99. GNU CPP has supported them
for a long time, but only with a named variable argument (‘args...’,
not ‘...’ and __VA_ARGS__). If you are concerned with portability to
previous versions of GCC, you should use only named variable
arguments. On the other hand, if you are concerned with portability to
other conforming implementations of C99, you should use only
__VA_ARGS__.
Change
#define DECLARE_C_ARRAY(__type, __name, __page, __args...) \
to
#define DECLARE_C_ARRAY(__type, __name, __page, ...) \
and
__args ;\
to
__VA_ARGS__;\
Unfortunately, this method does not work, if we exclude the args
In this case, remove the semicolon __VA_ARGS__\ (but pass-it when args is used).
An example: http://rextester.com/GYVS61567

Checking types of macro parameters at compile time

To check that two variables have the same structure type I use a macro
#define assert_same_struct_types(a, b) ((void) (sizeof((a)=(b))))
If some function-like macro
#define m(a,b) blablabla
assumes a and b should be of the same structure type, I add a compile time check:
#define m(a,b) (assert_same_struct_types(a, b), blablabla)
which provokes compiler error if caller of m(a,b) accidentally passes to m different types of structs.
However, this approach doesn't always work for builtin and pointer types due to implicit conversions between them.
So, is it possible to solve this problem for arbitrary types, not necessarily structs?
I need a solution for C89, however, it would be interesting to hear about C99 or C11 possibilities.
#define ASSERT_SAME_TYPE(a, b) ((void) (&(a) == &(b)))
will get you a compile diagnostic and an error with -Werror (for gcc or a similar option for other compilers).
Note that a lot of compilers have a non standard extension typeof operator to get the type of an object and this can be used to check two types are the same.
This questions asks about a C89 solution, so far I didn't find a good way to do this, so instead of relying on C89, you can check if the compiler supports typeof and use it when available. Its not ideal but means as long as some developers use GCC/Clang/IntelC, the error gets caught. of course, if you tell your compiler only to support C89 this isn't going to help.
It gives better type checking but obviously fails to be of any use at all when not supported.
#ifdef __GNUC__
#define CHECK_TYPE(var, type) { \
typeof(var) *__tmp; \
__tmp = (type *)NULL; \
(void)__tmp; \
} (void)0
#define CHECK_TYPE_PAIR(var_a, var_b) { \
typeof(var_a) *__tmp; \
__tmp = (typeof(var_b) *)NULL; \
(void)__tmp; \
} (void)0
#define CHECK_TYPE_PAIR_INLINE(var_a, var_b) ((void)({ \
typeof(var_a) *__tmp; \
__tmp = (typeof(var_b) *)NULL; \
(void)__tmp; \
}))
#else
# define CHECK_TYPE(var, type)
# define CHECK_TYPE_PAIR(var_a, var_b)
# define CHECK_TYPE_PAIR_INLINE(var_a, var_b) (void)0
#endif
/* inline type checking - can mix in with other macros more easily using the comma operator,
* C11 gives best results here */
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
# define CHECK_TYPE_INLINE(val, type) \
(void)((void)(((type)0) != (0 ? (val) : ((type)0))), \
_Generic((val), type: 0, const type: 0))
#else
# define CHECK_TYPE_INLINE(val, type) \
((void)(((type)0) != (0 ? (val) : ((type)0))))
#endif

Ways to ASSERT expressions at build time in C

I'm tidying up some older code that uses 'magic numbers' all over the place to set hardware registers, and I would like to use constants instead of these numbers to make the code somewhat more expressive (in fact they will map to the names/values used to document the registers).
However, I'm concerned that with the volume of changes I might break the magic numbers. Here is a simplified example (the register set is more complex):
const short mode0 = 0;
const short mode1 = 1;
const short mode2 = 2;
const short state0 = 0;
const short state1 = 4;
const short state2 = 8;
so instead of :
set_register(5);
we have:
set_register(state1|mode1);
What I'm looking for is a build time version of:
ASSERT(5==(state1|mode1));
Update
#Christian, thanks for the quick response, I'm interested on a C / non-boost environment answer too because this is driver/kernel code.
NEW ANSWER :
In my original answer (below), I had to have two different macros to support assertions in a function scope and at the global scope. I wondered if it was possible to come up with a single solution that would work in both scopes.
I was able to find a solution that worked for Visual Studio and Comeau compilers using extern character arrays. But I was able to find a more complex solution that works for GCC. But GCC's solution doesn't work for Visual Studio. :( But adding a '#ifdef __ GNUC __', it's easy to choose the right set of macros for a given compiler.
Solution:
#ifdef __GNUC__
#define STATIC_ASSERT_HELPER(expr, msg) \
(!!sizeof \ (struct { unsigned int STATIC_ASSERTION__##msg: (expr) ? 1 : -1; }))
#define STATIC_ASSERT(expr, msg) \
extern int (*assert_function__(void)) [STATIC_ASSERT_HELPER(expr, msg)]
#else
#define STATIC_ASSERT(expr, msg) \
extern char STATIC_ASSERTION__##msg[1]; \
extern char STATIC_ASSERTION__##msg[(expr)?1:2]
#endif /* #ifdef __GNUC__ */
Here are the error messages reported for STATIC_ASSERT(1==1, test_message); at line 22 of test.c:
GCC:
line 22: error: negative width in bit-field `STATIC_ASSERTION__test_message'
Visual Studio:
test.c(22) : error C2369: 'STATIC_ASSERTION__test_message' : redefinition; different subscripts
test.c(22) : see declaration of 'STATIC_ASSERTION__test_message'
Comeau:
line 22: error: declaration is incompatible with
"char STATIC_ASSERTION__test_message[1]" (declared at line 22)
ORIGINAL ANSWER :
I do something very similar to what Checkers does. But I include a message that'll show up in many compilers:
#define STATIC_ASSERT(expr, msg) \
{ \
char STATIC_ASSERTION__##msg[(expr)?1:-1]; \
(void)STATIC_ASSERTION__##msg[0]; \
}
And for doing something at the global scope (outside a function) use this:
#define GLOBAL_STATIC_ASSERT(expr, msg) \
extern char STATIC_ASSERTION__##msg[1]; \
extern char STATIC_ASSERTION__##msg[(expr)?1:2]
There is an article by
Ralf Holly that examines different options for static asserts in C.
He presents three different approaches:
switch case values must be unique
arrays must not have negative dimensions
division by zero for constant expressions
His conclusion for the best implementation is this:
#define assert_static(e) \
do { \
enum { assert_static__ = 1/(e) }; \
} while (0)
Checkout boost's static assert
You can roll your own static assert if you don't have access to a third-party library static assert function (like boost):
#define STATIC_ASSERT(x) \
do { \
const static char dummy[(x)?1:-1] = {0};\
} while(0)
The downside is, of course, that error message is not going to be very helpful, but at least, it will give you the line number.
#define static_assert(expr) \
int __static_assert(int static_assert_failed[(expr)?1:-1])
It can be used anywhere, any times.
I think it is the easiest solution.
Before usage, test it with your compiler carefully.
Any of the techniques listed here should work and when C++0x becomes available you will be able to use the built-in static_assert keyword.
If you have Boost then using BOOST_STATIC_ASSERT is the way to go. If you're using C or don't want to get Boost
here's my c_assert.h file that defines (and explains the workings of) a few macros to handle static assertions.
It's a bit more convoluted that it should be because in ANSI C code you need 2 different macros - one that can work in the area where you have declarations and one that can work in the area where normal statements go. There is a also a bit of work that goes into making the macro work at global scope or in block scope and a bunch of gunk to ensure that there are no name collisions.
STATIC_ASSERT() can be used in the variable declaration block or global scope.
STATIC_ASSERT_EX() can be among regular statements.
For C++ code (or C99 code that allow declarations mixed with statements) STATIC_ASSERT() will work anywhere.
/*
Define macros to allow compile-time assertions.
If the expression is false, an error something like
test.c(9) : error XXXXX: negative subscript
will be issued (the exact error and its format is dependent
on the compiler).
The techique used for C is to declare an extern (which can be used in
file or block scope) array with a size of 1 if the expr is TRUE and
a size of -1 if the expr is false (which will result in a compiler error).
A counter or line number is appended to the name to help make it unique.
Note that this is not a foolproof technique, but compilers are
supposed to accept multiple identical extern declarations anyway.
This technique doesn't work in all cases for C++ because extern declarations
are not permitted inside classes. To get a CPP_ASSERT(), there is an
implementation of something similar to Boost's BOOST_STATIC_ASSERT(). Boost's
approach uses template specialization; when expr evaluates to 1, a typedef
for the type
::interslice::StaticAssert_test< sizeof( ::interslice::StaticAssert_failed<true>) >
which boils down to
::interslice::StaticAssert_test< 1>
which boils down to
struct StaticAssert_test
is declared. If expr is 0, the compiler will be unable to find a specialization for
::interslice::StaticAssert_failed<false>.
STATIC_ASSERT() or C_ASSERT should work in either C or C++ code (and they do the same thing)
CPP_ASSERT is defined only for C++ code.
Since declarations can only occur at file scope or at the start of a block in
standard C, the C_ASSERT() or STATIC_ASSERT() macros will only work there. For situations
where you want to perform compile-time asserts elsewhere, use C_ASSERT_EX() or
STATIC_ASSERT_X() which wrap an enum declaration inside it's own block.
*/
#ifndef C_ASSERT_H_3803b949_b422_4377_8713_ce606f29d546
#define C_ASSERT_H_3803b949_b422_4377_8713_ce606f29d546
/* first some utility macros to paste a line number or counter to the end of an identifier
* this will let us have some chance of generating names that are unique
* there may be problems if a static assert ends up on the same line number in different headers
* to avoid that problem in C++ use namespaces
*/
#if !defined( PASTE)
#define PASTE2( x, y) x##y
#define PASTE( x, y) PASTE2( x, y)
#endif /* PASTE */
#if !defined( PASTE_LINE)
#define PASTE_LINE( x) PASTE( x, __LINE__)
#endif /* PASTE_LINE */
#if!defined( PASTE_COUNTER)
#if (_MSC_VER >= 1300) /* __COUNTER__ introduced in VS 7 (VS.NET 2002) */
#define PASTE_COUNTER( x) PASTE( x, __COUNTER__) /* __COUNTER__ is a an _MSC_VER >= 1300 non-Ansi extension */
#else
#define PASTE_COUNTER( x) PASTE( x, __LINE__) /* since there's no __COUNTER__ use __LINE__ as a more or less reasonable substitute */
#endif
#endif /* PASTE_COUNTER */
#if __cplusplus
extern "C++" { // required in case we're included inside an extern "C" block
namespace interslice {
template<bool b> struct StaticAssert_failed;
template<> struct StaticAssert_failed<true> { enum {val = 1 }; };
template<int x> struct StaticAssert_test { };
}
}
#define CPP_ASSERT( expr) typedef ::interslice::StaticAssert_test< sizeof( ::interslice::StaticAssert_failed< (bool) (expr) >) > PASTE_COUNTER( IntersliceStaticAssertType_)
#define STATIC_ASSERT( expr) CPP_ASSERT( expr)
#define STATIC_ASSERT_EX( expr) CPP_ASSERT( expr)
#else
#define C_ASSERT_STORAGE_CLASS extern /* change to typedef might be needed for some compilers? */
#define C_ASSERT_GUID 4964f7ac50fa4661a1377e4c17509495 /* used to make sure our extern name doesn't collide with something else */
#define STATIC_ASSERT( expr) C_ASSERT_STORAGE_CLASS char PASTE( PASTE( c_assert_, C_ASSERT_GUID), [(expr) ? 1 : -1])
#define STATIC_ASSERT_EX(expr) do { enum { c_assert__ = 1/((expr) ? 1 : 0) }; } while (0)
#endif /* __cplusplus */
#if !defined( C_ASSERT) /* C_ASSERT() might be defined by winnt.h */
#define C_ASSERT( expr) STATIC_ASSERT( expr)
#endif /* !defined( C_ASSERT) */
#define C_ASSERT_EX( expr) STATIC_ASSERT_EX( expr)
#ifdef TEST_IMPLEMENTATION
C_ASSERT( 1 < 2);
C_ASSERT( 1 < 2);
int main( )
{
C_ASSERT( 1 < 2);
C_ASSERT( 1 < 2);
int x;
x = 1 + 4;
C_ASSERT_EX( 1 < 2);
C_ASSERT_EX( 1 < 2);
return( 0);
}
#endif /* TEST_IMPLEMENTATION */
#endif /* C_ASSERT_H_3803b949_b422_4377_8713_ce606f29d546 */
Try:
#define STATIC_ASSERT(x, error) \
do { \
static const char error[(x)?1:-1];\
} while(0)
Then you can write:
STATIC_ASSERT(a == b, a_not_equal_to_b);
Which may give you a better error message (depending on your compiler).
The common, portable option is
#if 5 != (state1|mode1)
# error "aaugh!"
#endif
but it doesn't work in this case, because they're C constants and not #defines.
You can see the Linux kernel's BUILD_BUG_ON macro for something that handles your case:
#define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
When condition is true, this becomes ((void)sizeof(char[-1])), which is illegal and should fail at compile time, and otherwise it becomes ((void)sizeof(char[1])), which is just fine.
Ensure you compile with a sufficiently recent compiler (e.g. gcc -std=c11).
Then your statement is simply:
_Static_assert(state1|mode1 == 5, "Unexpected change of bitflags");
#define MODE0 0
#define MODE1 1
#define MODE2 2
#define STATE0 0
#define STATE1 4
#define STATE2 8
set_register(STATE1|STATE1); //set_register(5);
#if (!(5==(STATE1|STATE1))) //MY_ASSERT(5==(state1|mode1)); note the !
#error "error blah blah"
#endif
This is not as elegant as a one line MY_ASSERT(expr) solution. You could use sed, awk, or m4 macro processor before compiling your C code to generate the DEBUG code expansion of MY_ASSERT(expr) to multiple lines or NODEBUG code which removes them for production.

Resources