强制警告/错误

时间:2011-06-22 10:36:21

标签: visual-studio-2010 visual-c++

我想在我的代码中添加一些警告或错误。我正在使用visual studio 2010。

我用#error#warning在Xcode,但视觉工作室不知道的那些指令。

7 个答案:

答案 0 :(得分:6)

在搜索了不同的文章之后,我终于找到了适用于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 )

您可以将其用作:

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

注意TODO()也会生成编译器警告;如果您不想将TODO注册为警告,请改用:

#define TODO(text) MESSAGE( TODO: text )

如果要在警告/错误/ 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 )

答案 1 :(得分:5)

我知道这个建议有点晚了,但是......

您可以通过以下技巧实现您想要的目标:

// 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")

然后生成一条消息,例如:

#pragma message ( __MSG__ "my message" )

(来自http://rhubbarb.wordpress.com/2009/04/08/user-compilation-messages-c-or-c/

答案 2 :(得分:2)

没有找到关于警告消息的任何内容,但MSVC根据msdn page

创建了编译错误,就像xcode'#error message`一样

答案 3 :(得分:0)

它对我有用的方式:

#define _message_ "Warning Msg: "
#pragma message(_message_"Need to do something")

答案 4 :(得分:-1)

您可以使用#pragma warning ...

Mandatory read

答案 5 :(得分:-1)

MSVC使用

#pragma error( "message" )

#pragma warning( "message" )

指令,而GCC省略pragma s。

答案 6 :(得分:-3)

为什么不使用

#warning WarningMessage

或可能是

#error ErrorMessage
相关问题