objective-cclangllvmobjective-c-blocksgnustep

Using Objective-C Lambda syntax with GNUStep


Objective-C has a Lambda-like syntax called Blocks that was introduced by Clang, but it requires runtime support. How can I use it when my environment is GNUStep instead of Apple's runtime?


Solution

  • Simple code to test and run (t.m):

    #import <Foundation/NSAutoreleasePool.h>
    #import <Foundation/NSException.h>
    #import <Foundation/NSDebug.h>
    #import <Foundation/NSObject.h>
    #import <Foundation/NSString.h>
    #import <Foundation/NSObjCRuntime.h>
    
    #include <string.h>
    
    #if defined(GNUSTEP)
    #import <GNUstepBase/GSObjCRuntime.h>
    #else
    #include <objc/runtime.h>
    #endif
    
    void test(void (^callback)(void))
    {
        callback();
    }
    
    int main(int argc, char *argv[])
    {
        @autoreleasepool
        {
            int multiplier = 7;
            int (^myBlock)(int) = ^(int num)
            {
                return num * multiplier;
            };
    
            NSLog(@"%d", myBlock(3));
    
            test(^(void)
            { 
                NSLog(@"Inside");
            });
    
            NSLog(@"BLAH");
        }
    
        return 0;
    }
    

    Tested on Ubuntu 16

    Install:

    apt-get install -y build-essential gobjc gobjc++ gnustep gnustep-devel libgnustep-base-dev clang gnustep-make llvm libblocksruntime-dev
    

    Compile:

    clang -I `gnustep-config --variable=GNUSTEP_SYSTEM_HEADERS` -L `gnustep-config --variable=GNUSTEP_SYSTEM_LIBRARIES` -lgnustep-base -fconstant-string-class=NSConstantString -D_NATIVE_OBJC_EXCEPTIONS -fblocks -lobjc -o t t.m -lBlocksRuntime
    

    Run:

    ./t
    

    If you are missing the objc/runtime.h download and extract the GNUStep libobjc:

    wget http://download.gna.org/gnustep/libobjc2-1.6.tar.gz
    tar xzvf libobjc2-1.6.tar.gz
    cp -r libobjc2-1.6/objc /usr/include/GNUstep