首页 > 解决方案 > GCC 不合格?

问题描述

我知道很少有编译器实际上支持 C11 线程(这很可悲,但无论如何)。C11 标准要求不支持线程的实现定义__STDC_NO_THREADS__. 然而这个程序似乎给出了一个错误:

#include <stdio.h>
#ifndef __STDC_NO_THREADS__
    #include <threads.h> //error is here
#endif // __STDC_NO_THREADS__

int main(void)
{
    #ifdef __STDC_NO_THREADS__
        printf("There are no threads");
    #else
        printf("There are threads");
    #endif // __STDC_NO_THREADS__
}

//Error at line 3: fatal error: threads.h: No such file or directory

编译器版本是 GCC 9.2.0 (Windows 10 x64),带有__STDC_VERSION__= 201710L(所以它是 C17)。如果你不知道,问题是我的编译器没有定义__STDC_NO_THREADS__or <threads.h>,它不符合 C11。问题可能是什么?

标签: cmultithreadingc11

解决方案


C11 之前的编译器和库不会定义__STDC_NO_THREADS__,支持线程的 C11 后的编译器和库也不会定义。因此,正确的检查需要如下所示:

#if __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__)
  #include <threads.h>

否则旧版本的编译器/库将无法工作。在您的情况下,您似乎在 Windows 下使用 Mingw,在这种情况下使用不兼容的 Microsoft CRT(它不符合 C99 及更高版本)。

更高版本的 gcc 使用更高版本的 libc 似乎可以与原始代码一起正常工作。

请注意,除非您使用-std=c17 -pedantic-errors. 我认为在这种特定情况下并不重要。


推荐阅读