Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MSVC equivalent of __attribute__ ((warn_unused_result))?

I'm finding __attribute__ ((warn_unused_result)) to be very useful as a means of encouraging developers not to ignore error codes returned by functions, but I need this to work with MSVC as well as gcc and gcc-compatible compilers such as ICC. Do the Microsoft Visual Studio C/C++ compilers have an equivalent mechanism ? (I've tried wading through MSDN without any luck so far.)

like image 590
Paul R Avatar asked Nov 19 '10 15:11

Paul R


3 Answers

It's _Check_return_. See here for examples of similar annotations and here for function behaviour. It's supported since MSVC 2012.

Example:

_Check_return_
int my_return_must_be_checked() {
    return 42;
}
like image 89
Albert Avatar answered Nov 06 '22 20:11

Albert


UPDATE FOR MSVC 2012 AND LATER

Many thanks to @Albert for pointing out that MSVC now supports the annotation _Check_return_ as of Visual Studio 2012 when using SAL static code analysis. I'm adding this answer so that I can include a cross-platform macro which may be useful to others:

#if defined(__GNUC__) && (__GNUC__ >= 4)
#define CHECK_RESULT __attribute__ ((warn_unused_result))
#elif defined(_MSC_VER) && (_MSC_VER >= 1700)
#define CHECK_RESULT _Check_return_
#else
#define CHECK_RESULT
#endif

Note that, unlike gcc et al, (a) MSVC requires annotations on both declaration and definition of a function, and (b) the annotation needs to be at the start of the declaration/definition (gcc allows either). So usage will typically need to be e.g.:


// foo.h

CHECK_RETURN int my_function(void); // declaration


// foo.c

CHECK_RETURN int my_function(void)  // definition
{
    return 42;
}


Note also that you'll need the /analyze (or -analyze) switch if compiling from the command line, or the equivalent if using the Visual Studio IDE. This also tends to slow the build down somewhat.

like image 24
Paul R Avatar answered Nov 06 '22 20:11

Paul R


Some editions of VisualStudio come packaged with a static analysis tool that used to be called PREFast (Now called simply "Code Analysis for C/C++"). PREFast uses annotations to mark up code. One of those annotations, MustCheck, does what you're looking for.

like image 5
John Dibling Avatar answered Nov 06 '22 20:11

John Dibling