Sunday, July 5, 2009

How to compile command line utility for iPhone using XCode gcc


echo 'main() { printf("Hello, world!\n"); }' > hello.c

compile hello.c

/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.0 -arch armv6 -mthumb -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.2.sdk -o hello hello.c

compile with framework

/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.0 -arch armv6 -mthumb -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.2.sdk -framework Foundation -framework CoreFoundation -lobjc -std=c99 main.m -o main

codesign in Mac, if you have developer or self-signed certificate (can't codesign it when in ssh session)

export CODESIGN_ALLOCATE=/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/codesign_allocate; codesign -f -s "iPhone Developer" hello

or you can codesign in iPhone, that is, send the binary to iPhone and then fake codesign it

ldid -S hello

This is how to use as (assembler) to compile hello.s to ARM thumb binary
/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/as -arch armv6 hello.s -o hello

# GAS filename : hello.s
# use as to compile
# /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/as -arch armv6 hello.s -o hello
# use otool to disassemble
# otool -tv hello

  .globl _main
  .code 16
  .thumb_func _main
  push {r7, lr}
  add r7, sp, #0
  add r3, pc
  mov ip, r3
  mov r3, ip
  mov r0, r3
  pop {r7, pc}



alexwhittemore said...

This is exactly the post I was looking for the other day, thanks! Do you happen to have an Xcode project template handy for making CLI/daemon programs IN the Xcode environment, though? That'd be mighty handy.

Anonymous said...


After compiling hello.c, how can I test it on simulator ?

Thanks in advance

Audiophilip said...

@Anonymous: you can't, the compiled app is an ARM binary, not Intel. (The simulator runs Intel binaries.)

Anonymous said...

How do I use iOS APIs to write command line tools for iOS (not using Xcode)? I am trying to use the security framework in a small application. Thanks.