Saturday, March 16, 2013

Shebang Objective-C

Nicolas Bouilleaud has a clever trick for making Objective-C source files self-compiling (via Romain Briche):

The idea is to play with shell and C comments so that the file is both a valid shell script and an Objective-C program. The shell script calls clang to compile itself, and then runs the output executable.

I’ve fixed the quoting so that it also works when the path contains a space:

/*/../bin/ls > /dev/null
clang "$0" -o "$COMPILED" -framework Foundation;
"$COMPILED"; rm "$COMPILED"; exit;

#import <Foundation/Foundation.h>
int main(int argc, char *argv[])
        NSLog(@"Hello %@",NSProcessInfo.processInfo.environment[@"USER"]);
    return 0;

Make the .m file executable and you can run it from Terminal. Unfortunately, it won’t run from BBEdit’s #! menu because the file doesn’t actually begin with #!.

4 Comments RSS · Twitter

[...] See also: Shebang Objective-C. [...]

Here's a simpler version, equivalent to the first five lines:

//bin/echo -n ; clang "$0" -framework Foundation && ./a.out ; rm -f a.out ; exit

[…] (adapted from this comment) […]

Leave a Comment