Solarian Programmer

My programming ramblings

Objective-C blocks on Windows with Clang

Posted on March 25, 2012 by Paul

In my last post I’ve shown you how to develop Objective-C code on Windows with Clang and GNUstep. I’ve also presented a small Objective-C program that uses the new ARC syntax.

Today I will show you how to compile on Windows an Objective-C program that contains blocks. Strictly speaking Apple’s blocks syntax is an extension to the C language.

A block in Objective-C is similar with lambdas and closures from other languages. The purpose of this article is not to give you an exhaustive introduction to the block syntax. My intention here was only to show you how to enable the block syntax in Objective-C on Windows.

This a small Objective-C code that exemplifies the use of block syntax:

 1 #import <Foundation/Foundation.h>
 2 
 3 int (^result)(int, int) = ^(int a, int b) {
 4     int c;
 5     c = a + b;
 6     return c;
 7 };
 8 
 9 int main() {
10     @autoreleasepool {
11         int a,b;
12         a = 5;
13         b = -2;
14         NSLog(@"%d + %d = %d", a, b, result(a,b));
15     }
16     return 0;
17 }

Save the above code in a file named test.m. In order to succesfully compile test.m you will need to also create a make file, save the next piece of code in a file named GNUmakefile:

1 include $(GNUSTEP_MAKEFILES)/common.make
2 
3 TOOL_NAME = test
4 test_OBJC_FILES = test.m
5 
6 include $(GNUSTEP_MAKEFILES)/tool.make

Let’s compile test.m with Clang:

1 make CC="clang -fblocks"

In the above I’ve specifically instructed make to use Clang as the default compiler and to enable blocks support.

You can run your executable with:

1 ./obj/test

You can also put the block code inside the main function (a block can be defined inside a function) if you want:

 1 #import <Foundation/Foundation.h>
 2 
 3 int main() {
 4     @autoreleasepool {
 5         int (^result)(int, int) = ^(int a, int b) {
 6             int c;
 7             c = a + b;
 8             return c;
 9         };
10 
11         int a,b;
12         a = 5;
13         b = -2;
14         NSLog(@"%d + %d = %d", a, b, result(a,b));
15     }
16     return 0;
17 }

If you want to learn more about Objective-C I recommend you two books: Programming in Objective-C by Stephen G. Kochan and Objective-C Programming by Aaron Hillegass.


Show Comments