为什么要为同名函数定义宏? [英] Why define a macro to a function with the same name?

查看:18
本文介绍了为什么要为同名函数定义宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 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

#define 到底有什么作用?什么时候需要这样做?

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

推荐答案

有时 Linux 内核中的某些架构不提供某些功能,例如 arch_atomic_sub_and_test.这允许在不破坏其他架构的情况下有条件地提供这些功能.

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.

#define 允许您使用 #ifdef 测试函数是否存在:

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

例如,这就是它在 Linux 内核中的使用方式(来自 include/asm-generic/atomic-instrumented.h):

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

这篇关于为什么要为同名函数定义宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆