How to raise warning if return value is disregarded?

后端 未结 8 1016
北海茫月
北海茫月 2020-11-27 03:35

I\'d like to see all the places in my code (C++) which disregard return value of a function. How can I do it - with gcc or static code analysis tool?

Bad code exampl

8条回答
  •  再見小時候
    2020-11-27 04:02

    You want GCC's warn_unused_result attribute:

    #define WARN_UNUSED __attribute__((warn_unused_result))
    
    int WARN_UNUSED f(int z) {
        return z + (z*2) + z/3 + z*z + 23;
    }
    
    int main()
    {
      int i = 7;
      f(i); ///// <<----- here i disregard the return value
      return 1;
    }
    

    Trying to compile this code produces:

    $ gcc test.c
    test.c: In function `main':
    test.c:16: warning: ignoring return value of `f', declared with
    attribute warn_unused_result
    

    You can see this in use in the Linux kernel; they have a __must_check macro that does the same thing; looks like you need GCC 3.4 or greater for this to work. Then you will find that macro used in kernel header files:

    unsigned long __must_check copy_to_user(void __user *to,
                                            const void *from, unsigned long n);
    

提交回复
热议问题