MSVC equivalent of

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.)


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;
}

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 eg:


// 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.


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.

链接地址: http://www.djcxy.com/p/72522.html

上一篇: 在MSVC 2010中使用Clang

下一篇: MSVC相当于