Linux 模块 __must_check 注释

Linux module __must_check annotation

我正在学习 Linux 内核模块开发。我阅读了文章和教程,并找到了一个提供简单字符设备源代码的站点。

在代码中,__must_check 用于一个函数。

这是原型:

__must_check int register_device(void);

这是函数:

int register_device(void)
{
  int result = 0;

  printk( KERN_NOTICE "Simple-driver: register_device() is called." );

  result = register_chrdev( 0, device_name, &simple_driver_fops );
  if( result < 0 )
  {
     printk( KERN_WARNING "Simple-driver:  can\'t register character device with errorcode = %i", result );
     return result;
  }

  device_file_major_number = result;
  printk( KERN_NOTICE "Simple-driver: registered character device with major number = %i and minor numbers 0...255"
              , device_file_major_number );

  return 0;
}

__must_check有什么用?这是我发现的唯一使用它的代码。

__must_check 定义为:

#define __must_check __attribute__((warn_unused_result))

引用自Common Function Attributes

The warn_unused_result attribute causes a warning to be emitted if a caller of the function with this attribute does not use its return value. This is useful for functions where not checking the result is either a security problem or always a bug, such as realloc.

这也适用于 clang and Intel compiler

如果未使用 return 值,此宏会要求编译器发出警告。这对于函数 return 值很重要,可以指示成功或失败,如 scanfprintf,或函数 return 内存,如 mallocrealloc