Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clang block in Linux?

Tags:

c

linux

clang

block

Clang has a very cool extension named block bringing true lambda function mechanism to C. Compared to block, gcc's nested functions are quite limited. However, trying to compile a trivial program c.c:

#include <stdio.h>

int main() {
    void (^hello)(void) = ^(void) {
        printf("Hello, block!\n");
    };
    hello();
    return 0;
}

with clang -fblocks c.c, I got

/usr/bin/ld.gold: /tmp/cc-NZ7tqa.o: in function __block_literal_global:c.c(.rodata+0x10): error: undefined reference to '_NSConcreteGlobalBlock'
clang: error: linker command failed with exit code 1 (use -v to see invocation)

seems I should use clang -fblocks c.c -lBlocksRuntime, but then I got

/usr/bin/ld.gold: error: cannot find -lBlocksRuntime
(the rest is the same as above)

Any hints?

like image 995
xiaq Avatar asked May 06 '11 05:05

xiaq


1 Answers

Technical background information:

Blocks themselves are language feature but they also require some runtime support. So either the compiler has to provide a runtime library and statically link it into the build product or the system must provide such a runtime library the build product can be linked against.

In case of macOS, the blocks runtime is part of libSystem and as all executable and dynamic libraries on macOS are linked against libSystem, they all do have blocks support.

On a Linux system, such runtime support would typically added to the libC library (glibc in most cases) if it was considered a core feature of the system or the language, yet as gcc currently has no support for blocks at all and its unknown if blocks will ever become an official C feature, Linux systems don't ship runtime support for blocks by default.

clang itself does offer a target-indepedent blocks runtime as part of the compiler runtime library, yet it is optional and many Linux systems don't seem to include in their clang install package. That's why the project blocksruntime has been created, that builds the clang blocks runtime support as an own library, which you can statically link into your projects or dynamically install onto your systems. The source code is available on GitHub.

Depending on your Linux distribution, a ready-to-use installer package may exist. Note that blocksruntime cannot just be compiled for Linux, it can also be compiled for FreeBSD or Windows (MinGW/Mingw-w64) or even for Mac if you don't want to use the runtime that Apple provides. Theoretically it should be portable to any platform that clang natively supports.

like image 185
Mecki Avatar answered Oct 17 '22 15:10

Mecki