Search code examples
cconditional-compilation

How to #ifdef the __builtin_prefetch function


How do I keep __builtin_prefetch() in my code, but make compilers that do not have it compile successfully? (Just doing nothing where it is found).


Solution

  • __builtin_prefetch() is recognised by the compiler (gcc) not the preprocessor, so you won't be able to detect it using the C preprocessor.

    Since an identifier with two leading underscores is reserved for use by the implementation (so any code you use which defines such an identifier has undefined behaviour) I'd do it the other way around.

    #ifdef __GNUC__
    #define do_prefetch(x) __builtin_prefetch(x)
    #else
    #define do_prefetch(x)
    #endif
    

    and then use

    do_prefetch(whatever);
    

    where needed.

    That way there is no code emitted unless it is actually needed.

    Since __builtin_prefetch() accepts a variable number of arguments, you might want to adapt the above to use variadic macros (C99 and later) - if you use it with different numbers of arguments in different places in your code.