How to check __builtin_ function is available on gcc

懵懂的女人 提交于 2021-01-27 05:21:14

问题


I need to know is there a method for gcc to check presence of those awesome __builtin_MY_DESIRED_FUNCTIONs

For example, I'd like to use __builtin_nan and be sure it is available for my program and it won't fail during compilation time.

I'll be more specific: on clang there is __has_builtin "checker" so we can write smth like

#if __has_builtin(__builtin_nan)

But I can't find analog for gcc.

And probably I can rely just on gcc, like "Oh, I'm on gcc now, just let's assume all of those __builtin_ are here like in example below..."

#if __GNUC__
double mynan = __builtin_nan("0");
#endif

And probably it will work, till someone put this "-fno-builtin" compilation flag.


回答1:


No, you will have to use __GNUC__ and __GNUC_MINOR__ (and __GNUC_PATCHLEVEL__ if you use such gcc versions) to test for each release specific builtin function (gcc releases can be found here)

For example:

/* __builtin_mul_overflow_p added in gcc 7.4 */
#if (__GNUC__ > 7) || \
         ((__GNUC__ == 7) && (__GNUC_MINOR__ > 3))
#define BUILTIN_MUL_OVERFLOW_EXIST
#endif

#ifdef BUILTIN_MUL_OVERFLOW_EXIST
int c = __builtin_mul_overflow_p (3, 2, 3) ? 0 : 3 * 2;
#endif

And there is an open bug for exactly what you are asking about, in here.




回答2:


Good news! a __has_builtin was added in GCC 10 (see change notes):

The special operator __has_builtin (operand) may be used in constant integer contexts and in preprocessor ‘#if’ and ‘#elif’ expressions to test whether the symbol named by its operand is recognized as a built-in function by GCC in the current language and conformance mode. It evaluates to a constant integer with a nonzero value if the argument refers to such a function, and to zero otherwise. The operator may also be used in preprocessor ‘#if’ and ‘#elif’ expressions. The __has_builtin operator by itself, without any operand or parentheses, acts as a predefined macro so that support for it can be tested in portable code. Thus, the recommended use of the operator is as follows:

#if defined __has_builtin
#  if __has_builtin (__builtin_object_size)
#    define builtin_object_size(ptr) __builtin_object_size (ptr, 2)
#  endif
#endif
#ifndef builtin_object_size
#  define builtin_object_size(ptr)   ((size_t)-1)
#endif


来源:https://stackoverflow.com/questions/54079257/how-to-check-builtin-function-is-available-on-gcc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!