c - 编译器如何以及为什么将 extern 函数替换为空函数?

标签 c linux macros usb extern

考虑 linux/drivers/usb/hid-core.c 中的以下代码:

static void hid_process_event (struct hid_device *hid,
                               struct hid_field *field,
                               struct hid_usage *usage,
                               __s32 value)
{
   hid_dump_input(usage, value);
   if (hid->claimed & HID_CLAIMED_INPUT)
         hidinput_hid_event(hid, field, usage, value);
#ifdef CONFIG_USB_HIDDEV
   if (hid->claimed & HID_CLAIMED_HIDDEV)
         hiddev_hid_event(hid, usage->hid, value);
#endif
}

如果未启用特定配置选项,作者不想在此处调用 hiddev_hid_event()。这是因为如果未启用配置选项,该功能甚至不会存在。

为了删除这个 #ifdef,对 include/linux/hiddev.h 进行了以下更改:

#ifdef CONFIG_USB_HIDDEV
   extern void hiddev_hid_event (struct hid_device *,
                                 unsigned int usage,
                                 int value);
#else
   static inline void
   hiddev_hid_event (struct hid_device
*hid,
                     unsigned int usage,
                     int value) { }
#endif

然后drivers/usb/hid-core.c改成了:

static void hid_process_event
                           (struct hid_device *hid,
                            struct hid_field *field,
                            struct hid_usage *usage,
                            __s32 value)
{
   hid_dump_input(usage, value);
   if (hid->claimed & HID_CLAIMED_INPUT)
         hidinput_hid_event(hid, field, usage, value);
   if (hid->claimed & HID_CLAIMED_HIDDEV)
         hiddev_hid_event(hid, usage->hid, value);
}

如果未启用 CONFIG_USB_HIDDEV,编译器将用空函数调用替换对 hiddev_hid_event() 的调用,然后完全优化掉 if 语句。

我无法理解的是编译器如何将对 hiddev_hid_event() 的调用替换为空函数。我看到的唯一区别是返回类型 extern void 已替换为 static inline void。这是否意味着所有未定义的外部函数都将自动变为空函数?

引用:http://www.linuxjournal.com/article/5780?page=0,3

最佳答案

函数实际上定义的,但是函数体是空的:

static inline void
hiddev_hid_event (struct hid_device *hid,
                 unsigned int usage,
                 int value) 
{ }

我想,用空主体优化掉内联函数是微不足道的。

关于c - 编译器如何以及为什么将 extern 函数替换为空函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10720282/

相关文章:

构造一个逻辑表达式,它将计算一个字节中的位

java - 我需要一些帮助将一些代码从 C 转换为 Java

php - 为什么我的服务器要加载这些 PHP 变量?

c - linux sendto() 正在刷新缓冲区?

c - 如何打印内存地址?

c - Linux POSIX C LibPCRE `double free or corruption (fasttop)` 崩溃

c - 是否可以在 C 中使用 Lisp 语法和前缀表示法?

c++ - 从可变宏参数创建成员

C++ 在可变参数宏中使用多个参数(实现可选参数)

c - 为什么 a+++++b 不起作用?