Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why define a macro to a function with the same name?

Tags:

c

linux-kernel

I found the code below in https://github.com/torvalds/linux/blob/master/arch/x86/include/asm/atomic.h

static __always_inline bool arch_atomic_sub_and_test(int i, atomic_t *v)
{
        return GEN_BINARY_RMWcc(LOCK_PREFIX "subl", v->counter, e, "er", i);
}
#define arch_atomic_sub_and_test arch_atomic_sub_and_test

what does the #define really do? When is it necessary to do so?

like image 805
Just a little noob Avatar asked Dec 10 '19 13:12

Just a little noob


Video Answer


1 Answers

Sometimes some architectures in the Linux kernel don't provide certain functions, such as arch_atomic_sub_and_test. This allows these functions to be conditionally provided without breaking other architectures.

The #define allows you to test for the existence of the function with #ifdef:

#ifdef arch_atomic_sub_and_test
// use arch_atomic_sub_and_test
#else
// some other equivalent code
#endif

or it can be used to error out if the function is not available:

#ifndef arch_atomic_sub_and_test
# error "arch_atomic_sub_and_test not available"
#endif

For example, this is how it's used in the Linux kernel (from include/asm-generic/atomic-instrumented.h):

#if defined(arch_atomic_sub_and_test)
static inline bool
atomic_sub_and_test(int i, atomic_t *v)
{
        kasan_check_write(v, sizeof(*v));
        return arch_atomic_sub_and_test(i, v);
}
#define atomic_sub_and_test atomic_sub_and_test
#endif
like image 181
S.S. Anne Avatar answered Oct 22 '22 14:10

S.S. Anne