1 MSVC编译器:
使用#pragma message来自定义警告信息和错误信息。
注意:C++标准并不支持 #pragma message,但是msvc支持。
而msvc支持的#pragma warning是大多是用来取消编译器警告,不支持抛出编译期警告,详情请参考官网 warning杂注。
/** Transform expression \a _exp_ to string format. */
#define __AUX_STR_EXP(_exp_) #_exp_
/** Transform \a _exp_ to string format. */
#define ___AUX_STR(_exp_) __AUX_STR_EXP(_exp_)
/** location file name and file line */
#define __LOCATION_STR __FILE__ "(" ___AUX_STR(__LINE__) ")"
/** define warning message throw */
#define throw_warning(_code_, _message_) message(__LOCATION_STR ": warning C" ___AUX_STR(_code_) ": " _message_)
#define throw_error(_level_, _code_, _message_) message(__LOCATION_STR ":" _level_ " error C" ___AUX_STR(_code_) ": " _message_)
// test
#pragma throw_warning(10000, "this is a compile time warning message.")
#pragma throw_error("", 10001, "this is a compile time error message.")
#pragma throw_error("fatal", 10002, "this is a compile time fatal error message.")
输出结果:
2 C++标准的编译期错误信息:
注意:C++标准并没有类似#pragma warning的编译期警告信息.
#error this is a compile time error message.
结果: