GCC #pragma停止编译

41

是否有GCC pragma指令可以停止、中断或中止编译过程?

我正在使用GCC 4.1,但我希望该pragma也可在GCC 3.x版本中使用。


1
如果您告诉我们为什么想要停止编译,我们可能能够提供更好的答案。 - Michael
GCC 3-4.1上的限制仍然相关吗? - ideasman42
7个回答

62

你可能想要使用#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

文件 stopthis.cpp

#include <iostream>

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

这里的限制是#error不能在宏内部使用,尽管问题模糊不清。 - ideasman42
6
我也曾这样想,但我的GCC(4.9)没有报错,程序继续执行,尽管它没有编译成功,但是它没有停止,这是一个bug还是你能确认一下?请帮我翻译。 - Alec Teal

21

我不知道#pragma,但是#error应该可以实现你需要的功能:

#error Failing compilation

如果出现错误,它将以“编译失败”为错误信息终止编译。


13

这有效:

 #include <stophere>

当 GCC 找不到包含文件时会停止编译。如果不支持 C++14,我希望GCC也停止编译。

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

这是最佳答案。它可以防止编译器继续运行并可能产生大量无用的错误,这些错误会在#error之后发生。那些后来的错误可能会误导一些人,因为它们很可能只是第一个错误的副作用。 - phatpaul

6

通常情况下,#error 足以满足需求(而且是可移植的),但有时您需要使用 pragma,特别是当您想在宏中可选地导致错误时。

以下是一个示例用法,依赖于 C11's_Generic_Pragma

该示例确保 var 不是 int *short *,但不是在编译时的 const int *

示例:

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

3
#pragma GCC error "error message"

Ref: 7 Pragmas


0

您可以使用:

#pragma GCC error "my message"

但这不是标准的。


0

另一种选择是使用static_assert

#if defined(_MSC_VER) && _MSC_VER < 1916
    static_assert(false, "MSVC supported versions are 1916 and later");
#endif

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接