停止编译的GCC #杂注

ckocjqey  于 2023-01-05  发布在  其他
关注(0)|答案(7)|浏览(169)

是否有GCC杂注指令可以停止、暂停或中止编译过程?
我使用的是GCC 4.1,但是我希望在GCC 3.x版本中也可以使用该杂注。

xxls0lw8

xxls0lw81#

您可能需要#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
文件 * 停止此.cpp*
#include <iostream>

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

u2nhd7ah2#

我不了解#pragma,但#error应该可以满足您的需要:

#error Failing compilation

它将终止编译并显示错误消息“编译失败”。

0x6upsns

0x6upsns3#

这是可行的:

#include <stophere>

GCC在找不到包含文件时停止。我希望GCC在不支持C++14时停止。

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

vom3gejh4#

虽然通常#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)
1sbrub3j

1sbrub3j5#

#pragma GCC error "error message"

参考:7 Pragmas

vmdwslir

vmdwslir6#

您可以使用:

#pragma GCC error "my message"

但它不是标准的。

qlzsbp2j

qlzsbp2j7#

另一种方法是使用static_assert

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

相关问题