user565452 user565452 - 11 months ago 82
Linux Question

Are Objective-C blocks supported by compilers on Linux?

How do I compile the following code on linux? Using Ubuntu 10.10 (Maverick Meerkat).

#include <stdio.h>
#include <stdlib.h>

int main() {
void (^block)() = ^{
printf("Hello world");

I tried:

gcc -x objective-c t.c

And got:

t.c: In function 'main':
t.c:5: error: expected identifier or '(' before '^' token

Any guidance on how to make this work is appreciated. Edited question based on feedback, thanks.

Answer Source

The official GCC does not include blocks support. For that, you either need to use Apple's patches, or use clang, an LLVM-based compiler that has good Objective-C support (because Apple has been funding its development). On linux, you're probably better off not trying to apply Apple's patches to GCC. Just go with clang.

However, simply having a compiler that supports blocks is not enough - the runtime also needs to support blocks. There are two runtimes you can use with GNUStep on linux, and there's one for BSD as well (libdispatch has been ported to FreeBSD, and it required a blocks-capable runtime).

The quickest way to get objective-c support with blocks on linux is probably to install the latest clang and the latest snapshot of GNUStep-base plus the ObjectiveC2 framework from GNUStep. It's not likely that your distro has any GNUStep-related packages that are new enough to work well with the newest runtimes and compilers.