Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
799 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...