Pages

Thursday, November 10, 2011

Generating custom warnings in VC

Hi! You might have already noticed that in C++ you can generate an error using the #error directive, but you cannot generate a warning in the similar way.

Wrong, you can… by using the following below trick.

So, lets look at a typical warning message the MSVC compiler produces:

d:\devel\root\project\main.cpp(33): warning C4244: 'initializing' : conversion from 'double' to 'int', possible loss of data

And you might noticed that Visual Studio somehow distincts errors and warning in output log and then reports them  via the error list. Well, it actually just read string patterns, so if you print a string using the warning pattern, you will get a warning! And the following macros will help you:

#define WARNING_NO_CODE(text) \ 
    __pragma(message( \
        __FILE__ "(" \
        _CRT_STRINGIZE(__LINE__) \
        "): warning: " text))

#define WARNING(code, text) \ 
    __pragma(message(__FILE__ "(" \
        _CRT_STRINGIZE(__LINE__) "): warning " \
        _CRT_STRINGIZE(code) ": " text))

You can use it, for example, for marking functions as not implemented, so that you won’t forget about them in future:

#define NOT_IMPLEMENTED() \
    WARNING_NO_CODE("Not implemented - " __FUNCTION__);\
    _ASSERTE(!"Not implemented - " __FUNCTION__);\
    throw std::runtime_error("Not implemented - " __FUNCTION__);

If you insert this in the body of your function, you will can a 'Not implemented' that points to this function warning during each compilation, so you will never forget about it! Though it won't affect warning counter... anyway.. Cheers!

No comments:

Post a Comment