36
votes

Is there a GCC pragma directive that will stop, halt, or abort the compilation process?

I am using GCC 4.1, but I would want the pragma to be available in GCC 3.x versions also.

6
We might be able to provide a better answer if you tell us why you want compilation to stop.Michael
Is the constraint on GCC 3-4.1 still relevant?ideasman42

6 Answers

56
votes

You probably want #error:

$ cd /tmp
$ g++ -Wall -DGoOn -o stopthis stopthis.cpp
$ ./stopthis

Hello, world

$ g++ -Wall -o stopthis stopthis.cpp

stopthis.cpp:7:6: error: #error I had enough

File stopthis.cpp

#include <iostream>

int main(void) {
  std::cout << "Hello, world\n";
  #ifndef GoOn
    #error I had enough
  #endif
  return 0;
}
20
votes

I do not know about a #pragma, but #error should do what you want:

#error Failing compilation

It will terminate compilation with the error message "Failing compilation".

8
votes

This works:

 #include <stophere>

GCC stops when it can't find the include file. I wanted GCC to stop if C++14 was not supported.

 #if __cplusplus<201300L
   #error need g++14
   #include <stophere>
#endif
6
votes

While typically #error is sufficient (and portable), there are times when you want to use a pragma, namely, when you want to optionally cause an error within a macro.

Here is an example use which depends on C11's _Generic and _Pragma.

This example ensures var isn't an int * or a short *, but not a const int * at compile time.

Example:

#define MACRO(var)  do {  \
    (void)_Generic(var,   \
          int       *: 0, \
          short     *: 0, \
          const int *: 0 _Pragma("GCC error \"const not allowed\""));  \
    \
    MACRO_BODY(var); \
} while (0)
2
votes
#pragma GCC error "error message"

Ref: 7 Pragmas

1
votes

You can use:

#pragma GCC error "my message"

But it is not standard.