Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a compiler supports static_assert?

I want to detect, in source file, if the compiler used supports static_assert.

like image 421
nialv7 Avatar asked Aug 28 '14 15:08

nialv7


People also ask

Where is static_assert defined?

static_assert is a keyword defined in the <assert. h> header. It is available in the C11 version of C. static_assert is used to ensure that a condition is true when the code is compiled.

What is the behavior if condition provided to static_assert is evaluated as false?

If the condition is true, the static_assert declaration has no effect. If the condition is false, the assertion fails, the compiler displays the message in string_literal parameter and the compilation fails with an error.

What is the difference between assert () and static_assert ()? Select one?

static_assert is meant to make compilation fail with the specified message, while traditional assert is meant to end the execution of your program.


1 Answers

In c11, static_assert is an assert.h macro that expands to _Static_assert.

You can just use:

#include <assert.h>

#if defined(static_assert)
// static_assert macro is defined
#endif

Note that some compilers (e.g., IAR) also have a static_assert keyword extension even if they don't support C11.

As mentioned in the comments you can also check for c11:

#if (__STDC_VERSION >= 201112L)
// it is c11, static_assert is defined when assert.h is included
#endif
like image 144
ouah Avatar answered Sep 20 '22 06:09

ouah