Ser*_*upu 10 visual-studio-2010 visual-c++
我想在我的代码中加入一些警告或错误.我正在使用visual studio 2010.
我曾经#error
和#warning
在Xcode,但视觉工作室不知道这些指令.
在搜索了不同的文章后,我终于找到了在Visual Studio 2010中运行的解决方案:
#define STRINGIZE_HELPER(x) #x
#define STRINGIZE(x) STRINGIZE_HELPER(x)
#define __MESSAGE(text) __pragma( message(__FILE__ "(" STRINGIZE(__LINE__) ")" text) )
#define WARNING(text) __MESSAGE( " : Warning: " #text )
#define ERROR(text) __MESSAGE( " : Error: " #text )
#define MESSAGE(text) __MESSAGE( ": " #text )
#define TODO(text) WARNING( TODO: text )
Run Code Online (Sandbox Code Playgroud)
你可以用它作为:
WARNING( This will be a compiler warning );
ERROR( This will be a compiler error );
MESSAGE( Well this is what I have to say about this code );
TODO( Still have to fix 3D rendering );
Run Code Online (Sandbox Code Playgroud)
注意,TODO()也会生成编译器警告; 如果您不想将TODO注册为警告,请改用:
#define TODO(text) MESSAGE( TODO: text )
Run Code Online (Sandbox Code Playgroud)
如果要在warnings/errors/TODO中显示函数名称,请改用:
#define WARNING(text) __MESSAGE( " : Warning: (" __FUNCTION__ "): " #text )
#define ERROR(text) __MESSAGE( " : Error: (" __FUNCTION__ "): " #text )
#define MESSAGE(text) __MESSAGE( ": (" __FUNCTION__ "): " #text )
#define TODO(text) __MESSAGE( " : Warning: TODO: (" __FUNCTION__ ") " #text )
Run Code Online (Sandbox Code Playgroud)
我知道这个建议有点晚了,但......
您可以通过以下技巧实现您想要的目标:
// stringised version of line number (must be done in two steps)
#define STRINGISE(N) #N
#define EXPAND_THEN_STRINGISE(N) STRINGISE(N)
#define __LINE_STR__ EXPAND_THEN_STRINGISE(__LINE__)
// MSVC-suitable routines for formatting <#pragma message>
#define __LOC__ __FILE__ "(" __LINE_STR__ ")"
#define __OUTPUT_FORMAT__(type) __LOC__ " : " type " : "
// specific message types for <#pragma message>
#define __WARN__ __OUTPUT_FORMAT__("warning")
#define __ERR__ __OUTPUT_FORMAT__("error")
#define __MSG__ __OUTPUT_FORMAT__("programmer's message")
#define __TODO__ __OUTPUT_FORMAT__("to do")
Run Code Online (Sandbox Code Playgroud)
然后生成一条消息,例如:
#pragma message ( __MSG__ "my message" )
Run Code Online (Sandbox Code Playgroud)
(来自http://rhubbarb.wordpress.com/2009/04/08/user-compilation-messages-c-or-c/)