为什么 .c 文件可以包含块?

Why can .c files contain blocks?

我认为块是 Objective-C 功能。最近我正在将块添加到一些 C 源文件中,我发现它只是编译 OK。

我很困惑,对于*.c文件,编译器(Clang)是否应该将其视为纯C文件,为什么它可以允许块?

实际上 Clang 引入了块

to C and, by extension, Objective-C, C++, and Objective-C++

您可以在 overview 中阅读此处。

当然,使用块会使您的源代码与 C11 标准不兼容,但是,您知道,只要您的代码仅适用于 Mac OS X...

编辑:块在 GCC 中也可用,我不知道。

块的添加方式使得它们也是 Apple 编译器中的 "C" 功能。

来自 Apple 的 Blocks Programming Topics

Blocks are available in GCC and Clang as shipped with the OS X v10.6 Xcode developer tools. You can use blocks with OS X v10.6 and later, and iOS 4.0 and later. The blocks runtime is open source and can be found in LLVM’s compiler-rt subproject repository. Blocks have also been presented to the C standards working group as N1370: Apple’s Extensions to C. As Objective-C and C++ are both derived from C, blocks are designed to work with all three languages (as well as Objective-C++). The syntax reflects this goal.