我有一个makefile可以执行多项操作,包括调用bash文件和制作C ++文件。在bash文件中,我有代码:
echo "${variable}: Error" 1>&2
exit 1
打印错误文本然后退出批处理文件和makefile,停止它。我想用C ++代码做同样的事情。我可以抛出一个错误并在抛出错误的地方停止C ++代码,但我似乎无法想办法让它停止makefile。有没有办法做到这一点?谢谢你的帮助。
编辑:在下面的评论中提到,但makefile编译代码然后在下一节中运行它,因此最好能够在编译错误和运行错误时突破makefile。 / p>
答案 0 :(得分:3)
由于您正在讨论Makefile,我假设您希望在C ++程序的编译期间停止Makefile(而不是执行生成的程序)。
如果是这种情况,请使用#error
预处理程序指令。
#if !defined(FOO) && defined(BAR)
#error "BAR requires FOO."
#endif
参考:
答案 1 :(得分:2)
要在C ++程序运行期间表示错误状态,您可以执行以下操作:
使用std::cerr
:
std::cerr << "This will not do!\n";
通过从main
返回非零值来传递将要理解的错误状态:
int main() {
// Your program
if (error_condition) {
std::cerr << "This will not do!\n";
return 1;
}
}
您还可以使用exit
中的#include <cstdlib>
功能从程序中的任何位置终止程序(可选择使用错误状态):
#include <cstdlib>
void not_main() {
std::exit(1); // Non-zero value here indicates error status to make
}
int main() {
not_main();
}