GCC 不符合?

Dar*_*tom 2 c multithreading c11

我知道很少有编译器真正支持 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
Run Code Online (Sandbox Code Playgroud)

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

Lun*_*din 5

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

#if __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__)
  #include <threads.h>
Run Code Online (Sandbox Code Playgroud)

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

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

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