Reputation: 361
I have a makefile that does multiple things, including calling a bash file and making a C++ file. In the bash file I have the code:
echo "${variable}: Error" 1>&2
exit 1
Which prints error text then exits the batch file and the makefile, stopping it. I want to do the same thing with the C++ code. I can throw an error and stop the C++ code at wherever the error was thrown, but I can't seem to figure out a way to make it stop the makefile as well. Is there a way to do this? Thanks for the help.
Edit: Mentioned in a comment below, but the makefile both compiles the code then runs it in the next section so it would be best to be able to break out of the makefile both on a compile error and a run error.
Upvotes: 2
Views: 209
Reputation: 22089
To signify an error status during runtime of a C++-program, you can do the following:
Printing an error to the error stream is done with std::cerr
:
std::cerr << "This will not do!\n";
Passing an error status that make will understand is done by returning a non-zero value from main
:
int main() {
// Your program
if (error_condition) {
std::cerr << "This will not do!\n";
return 1;
}
}
You can also terminate the program, optionally with an error status, from anywhere in the program using the exit
function from #include <cstdlib>
:
#include <cstdlib>
void not_main() {
std::exit(1); // Non-zero value here indicates error status to make
}
int main() {
not_main();
}
Upvotes: 2
Reputation: 137398
Since you're talking about Makefiles, I'm assuming that you want to stop the Makefile during the compilation of the C++ program (and not the execution of the resulting program).
If that's the case, use the #error
preprocessor directive.
#if !defined(FOO) && defined(BAR)
#error "BAR requires FOO."
#endif
Reference:
Upvotes: 3