Compiling C files for Mach-O ARM architecture, in OS X Lion

Yesterday I wanted to compile a .c code for ARM architecture using the iOS SDK on my Lion machine. I wanted to create object files and executable files that I can install on my jailbroken iPhone 4. I have explained the process here for you. I hope it will be of help.

We are going to be using the LLVM-GCC compiler. In OS X Lion, this compiler sits here:

/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/llvm-gcc-4.2

Also we need to pass the path to our iOS SDK, to the compiler so that it knows where to get the libraries and frameworks from. In OS X Lion with iOS SDK 5.1 installed, the path of the iOS SDK would be here:

/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk

So if your SDK version is different, you need to modify that path. Now let’s write a simple Hello World C code in a file named hello.c

#include <stdio.h>

int main(void){
printf(“Hello, World!\n”);
}

Now let’s go to Terminal and change your current working directory to the directory that contains the above hello.c file. Now let’s tell Terminal where our compiler and SDK folders are:

COMPILER=”/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/llvm-gcc-4.2″
SDKDIR=”/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk”

Now we are going to attempt to compile the hello.c source file for armv7 CPU architecture:

$COMPILER hello.c -o hello.o -c -arch armv7 -isysroot $SDKDIR

Now if you get an ls -la on your folder, you will also see an object file called hello.o. If you do the following:

file hello.o

You should see an output like this:

hello.o: Mach-O object arm

So now we have the object file. If you want to link this object file into an executable file, then you can do this:

LINKER=$COMPILER
$LINKER hello.o -o hello -arch armv7 -isysroot $SDKDIR

Note: the linker and compiler are both llvm-gcc-4.2 but we pass the -c to it to compile and if we skip -c, we will link, producing the final executable file.

Now you have 3 files

  • hello.c
  • hello.o
  • hello
The first one is your source file, the second one is the compiled file and the third one is the linked (executable) file. So now do this:
file hello
You should be able to see the following output:
hello: Mach-O executable arm

That’s it. If you have any questions, let me know in the comment section below.

About these ads