Os Eclipse Iphone CDT PDF
Os Eclipse Iphone CDT PDF
CDT
How Windows and Linux developers can bypass the iPhone
SDK and write iPhone apps using open source tools
PJ Cabrera ([email protected])
Freelance Software Developer and Writer
Freelance
30 Sep 2008
Learn how to use the Eclipse C Development Toolkit (CDT) to program native
applications for the Apple iPhone, using open source tools to enable iPhone OS
development on any Eclipse-supported platform.
This tutorial explores the Eclipse C Development Tooling (CDT) project and how it
allows you to work with C- and C++-based projects. In this tutorial, you install open
source tools to help develop native applications for the iPhone platform on Windows
and Linux, and learn about the source code of a basic iPhone application in
Objective-C.
Objectives
This tutorial shows how you can use Eclipse and the CDT plug-ins to develop for the
iPhone platform, using the open source GNU Compiler Collection (GCC). You use
these tools to compile an Objective-C example application for the iPhone.
Prerequisites
This tutorial is written for C and C++ programmers whose skills and experience are
at a beginning to intermediate level. You should have a general familiarity using a
UNIX® command-line shell and a working knowledge of the C language. The iPhone
Cocoa Touch native application development frameworks are written in Objective-C
and are based on the Cocoa frameworks used in Mac OS X. Familiarity with
Objective-C and Mac OS X Cocoa application development frameworks is not
assumed, but such skills are helpful in making sense of the iPhone platform. Further
study of Cocoa development is recommended after following this introductory
tutorial.
System requirements
To follow along with this tutorial, you need:
The iPhone platform is based on the same Darwin operating system and
Objective-C Cocoa frameworks as Mac OS X, modified to fit on an Advanced RISC
Machines (ARM)-based embedded device with 128 MB of RAM, several gigabytes
of flash storage, and a multi-touch touchscreen. The platform also features an
accelerometer for detecting device orientation and movement, and 3-D graphics that
rival the capabilities of the Sony PSP and PS2 consoles.
As with NextStep and OpenStep, the development tools for Mac OS X and the
iPhone are based on Objective-C. Apple created a development framework based
on Objective-C for Mac OS X: Cocoa. The iPhone platform is based on the same
Darwin operating system core and Objective-C Cocoa framework as the Mac OS X
platform.Cocoa Touch is the development framework for the iPhone.
C++ and Objective-C are object-oriented extensions of the C language. But there
are key differences between C++ and Objective-C. Objective-C is a language and an
object-lifetime management runtime, whereas C++ is only a language, and the
programmer manages object lifetime entirely. The other main difference is the
syntax of object-oriented operations between the two. C++ extends the C struct
manipulation syntax, whereas Objective-C invents a new syntax with scoped square
brackets. Table 1 presents the main syntactic differences between the languages.
on classes or objects.
Objective-C invented a
different syntax with
scoped square brackets
and named parameters
terminated by colons.
Object instantiation UIView UIView In C++ the new
contentView = new contentView = keyword allocates
UIView(x, y, [[UIView alloc] memory for the object
width, height); initWithFrame: and calls one of the
CGRectMake(x, y, declared constructors
width, height)]; that most closely
matches the
parameters you pass in
the code. In
Objective-C, you call
the alloc method of
the class, which returns
an uninstantiated object
of that class. Then, you
call an init method on
the object returned by
alloc to set initial
values for the instance.
Class definitions C++ extends the C
class MyClass @interface MyClass : NSObject
struct{ definition
{ int myVariable; syntax by adding the
private: } ability to define
int myVariable; methods within a
void privateMethod(); @private struct or class. It
public: - (void)privateMethod; also adds the private
void setMyVariable(int param);
@public and public keywords
} - (void)setMyVariable: (int)param;
(as well as the
@end protected keyword
not used in this
example) to provide the
object-oriented feature
of encapsulation. In
Objective-C, the
@interface and @end
keywords are used to
define the attributes of
a class. Objective-C
uses the keywords
@private, @public,
and @protected with
equivalent meaning to
the similarly named
keywords in C++.
Classes in Objective-C
have to inherit from
another class. In this
example, the class
NSObject, whereas in
Jailbreak
When Apple announced the iPhone, the company downplayed the lack of an
unfettered application development environment, citing the need to protect the
cell-provider data network from malicious applications running on hacked phones.
When introducing the iPhone software development kit (SDK) in March 2008, one of
the key features was that the iPhone would only be allowed to run applications
signed by Apple using unique keys handed out to iPhone developers with whom
Apple has a relationship.
Since September 2007, a group calling itself the iPhone Dev Team developed
methods for removing the restrictions Apple devised to limit what could be done on
the iPhone. The group helped create the open source tools used to compile
programs for the device.
The iPhone Dev Team also created tools that remove restrictions from the iPhone
and iPod Touch. These tools permit iPhone owners to use their devices on networks
other than AT&T in the United States or to use the iPhone in countries without an
iPhone carrier. This process is called unlocking.
This tutorial covers "jailbreaking" only, which consists of allowing applications not
blessed by Apple to run on the device. Note that the use of these tools is not
supported by Apple, and their use may void the device's warranty if Apple has
evidence of third-party software modification.
As when using any other unfamiliar software, take your time before
you start. Read ahead to understand where you are going and be
certain you understand the possible outcomes to using these tools.
QuickPwn performs the jailbreaking task quickly. All that's required is to download
the correct version of the iPhone OS for your device (only iPhone OS versions 2.0
through 2.0.2 are supported at the time of this writing). Then, connect it to your
computer with the USB charging/data cable and put your iPhone in what is called
DFU mode, as per the instructions in the software. In less than 10 minutes, your
device is jailbroken.
designated iPhone service provider for your country, the iPhone Dev Team offers
Xpwn, Pwnage (see Figure 1), or WinPwn.
But to tap that command-line and enable development, you must install on the
device the OpenSSH secure remote shell client and server, the Linker Identity
Editor, and the Respring utility to restart the dashboard. These enable you to
transfer your programs to the iPhone and log in to execute commands on the device,
sign your code with a bogus key to make the iPhone run it, and reset your
dashboard to show your newly copied applications.
Software installation is made simple on jailbroken iPhones through the use of Cydia,
a package manager front end for APT. Linux users are probably giddy right now as
the previous sentence sinks in: APT package management, the one used by
Debian-based Linux distributions including Ubuntu? Yes, indeed, my friends. Yes,
indeed.
Before running Cydia, make sure you're connected to either the cell data network or
WiFi — preferably the latter, as OpenSSH is a bit hefty. Run Cydia, wait for it to
download package manifests from the built-in sources, then click Search at the
bottom of the Cydia window. Search for openssh and install it. Then search for ldid
and install it. Finally, search for respring and install it.
Now that you have installed OpenSSH on your iPhone, you need to secure it. All
iPhones come with two user accounts: root and mobile. Both have the same
password: alpine. Log in to your device and change the password for these two
accounts. Make them different from each other — and memorable. Connect your
device to your WiFi network if you haven't done so already and find its IP address
using the Settings application.
Note: The first time you connect to the iPhone through OpenSSH, the device can
take a minute or so to appear to respond because it is generating unique system
keys. Subsequent connections should be nearly instantaneous.
You're ready to get started creating your own software for the device. The next
section shows how to install the toolchain that makes programming the iPhone
possible.
actually available. Members of the iPhone Dev Team have produced instructions
and patches to enable developers in other platforms to build and use it. That's what
we do next.
There are a couple of requirements before we begin. You must already have a
toolchain installed for the platform you're running. You need tools installed that can
convert the GCC source code into executables for your operating system.
Depending on your platform, you can install tools for Windows or Linux.
1. Downloaded the Cygwin setup program, run it and click Next at every
prompt until you come to the window shown below.
Figure 2. Cygwin root directory selection part of the installation
2. Make sure the options at the bottom of this window match those in Figure
2 or you'll have trouble working with the example code and toolchain
sources you download in the next sections of this tutorial. If you install
Cygwin to a different directory from the one in Figure 2, you must keep
that directory in mind and make modifications to the steps given in the
other sections of this tutorial to match your installation choice. I suggest
you keep things simple and follow the example.
7. For the autoconf, binutils, bison, flex, gcc-c++, and make packages, click
Skip to the left of the package you want to include in the installation, as
shown below. Clicking Skip once selects the Binary column check box
and the version number of the package to show where the "skip" was.
Note that the actual version numbers may differ from what is shown
because packages are updated continuously.
Figure 6. Select the packages to include in the installation
10. Click Next. Cygwin setup downloads the packages from the mirror site
and installs itself at the directory specified earlier. This process can take
upwards of an hour, even on 2-megabit broadband and faster, because
those mirrors are in high demand, not only for Cygwin packages but for
other open source software they mirror.
When Cygwin finishes downloading and installing packages, you can choose
whether you want Cygwin to install shortcut icons on the desktop or in the Start
menu, and you're done. You have just installed the GCC toolchain and a complete
UNIX-like environment that runs natively on Windows. You can now go directly to
"installing the iPhone toolchain from source."
If you're using SuSE or Red Hat Linux or any derivative of these, such as CentOS,
you need to install autoconf, binutils, bison, gcc, g++, flex, and make with yum.
sudo yum install bison flex autoconf binutils gcc gcc-c++ make
If you're using any other Linux distribution, consult your documentation for
instructions on installing packages. You want to install the packages listed for
yum-based systems. Be aware that gcc-c++ may be called something else on your
system or may be included with GCC. When the requisite packages are installed,
you can move on to "installing the iPhone toolchain from source."
I packaged the source code needed to compile the toolchain and provide a link in
the Resources section. Download that file and copy it to the home folder of your user
account. If you're using Cygwin, copy it to C:/cygwin/home/yourusername if you
installed Cygwin to the recommended directory. Extract the package with your
favorite gzipped tar-compatible tool, and you'll find a folder named
The firmware restore file is nothing more than a ZIP file. After you have the firmware,
change the extension to .zip and open it with any extraction utility for your platform.
Inside the ZIP file, you'll find a file called 018-3785-2.dmg. Copy this DMG file to the
home folder of your user account, right next to the iphone-2.0-toolchain folder from
earlier. (Windows users: We refer to the Cygwin user home folder, not your Windows
user home folder.)
This command compiles the DMG decryptor code to an executable file named
vfdecrypt on your home folder. Now you can decrypt the DMG file.
Notice that this is two separate lines, and don't miss that backslash (\) at the end of
the first line. It is really a single command, but we split it into two lines with the
backslash to avoid ambiguity caused by the sheer length of the command. You may
want to paste the two lines in rather than manually enter the monstrous decryption
key.
Now that you've decrypted the DMG, mount it, and extract the contents. Linux users
can install HFS drivers and mount the DMG. It's OK if your distro only has read-only
HFS drivers, as you just want to copy some files. Windows users can use either
PowerISO or Transmac (see Resources) to open the DMG file and copy the files you
want.
4. Move the lib folder from your desktop into the iphone-fs/usr folder.
cd ~/iphone-2.0-toolchain
./make-toolchain
These commands finally start the process of compiling the iPhone toolchain and
installing it to /usr/local on your system. The process takes about two hours on a
2.0-GHz Core 2 Duo MacBook running Microsoft Windows XP inside VMware with
640 MB of RAM allocated to the virtual machine (VM). After a wait of a few minutes,
you'll see a lot of gibberish scroll by very quickly. Don't worry: That means it's
working! The only time you should be concerned is if it stops and returns to the shell
prompt after displaying several error lines, such as those below.
If the make process stops but you don't see any error lines like those in Figure 12,
you have successfully completed the compilation process. Now that you have built
the toolchain, you're ready to get started creating your own software for the iPhone.
Next, you must install Eclipse CDT and you can explore how it lets you program C
and C++ within Eclipse.
If you don't already have Eclipse or if you don't feel like integrating all these plug-ins
into your installation of Eclipse, check out the EasyEclipse project (see Resources)
and download the EasyEclipse for the C and C++ distribution. EasyEclipse includes
the Eclipse, Eclipse CDT, Subclipse, and CVS plug-ins for managing your source
revisions, as well as several plug-ins for syntax highlighting and editor default
handing of different languages, including Objective-C. Find all of this in one simple,
single download for Windows, Linux, and Mac OS X.
If you already have Eclipse installed and have no problems adding plug-ins
manually, you can add both to your copy of Eclipse easily. To install the Color Editor,
download the plug-in and drop the JAR into your Eclipse plugins directory. To install
the Eclipse CDT, go to the Eclipse CDT download page and find the correct URL for
your version of Eclipse. In Eclipse, go to Help > Software Update > Find and
Install... > Search for new features to install > New Remote Site... and enter the
correct CDT URL for your version of Eclipse. Proceed with the installation and
restart Eclipse (see Resources for the CDT and Color Editor).
1. Run Eclipse. From the workbench, choose File > New > Project to bring
up the New Project window.
2. Choose General > Project, and then click Next, as shown below.
Figure 13. The New Project window
CC=gcc
CXX=g++
LD=$(CC)
all: HelloWorld
HelloWorld: HelloWorld.o
$(LD) $(LDFLAGS) -o $@ $^
%.o: %.c
$(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@
clean:
rm *.o HelloWorld
#include <stdio.h>
int main(void) {
printf("Hello, world!\n");
return 0;
}
Typing make at the command line causes a program called make to interpret the
makefile, which effectively tells make that it should compile HelloWorld.c into an
object file called HelloWorld.o, link HelloWorld.o implicitly with the standard C
libraries, and produce an executable file called HelloWorld. That is the meaning of
the two commands produced as console output by make.
If you have programmed in C on UNIX before, this is probably not exciting news.
However, it's wise to verify that the simple C code and makefile work correctly by
executing the compiled and linked program with the following command:
./HelloWorld
This should produce the output "Hello, world!" in the console. Now, modify the
makefile and produce an executable file that runs on the iPhone using your new
toolchain.
CC=/usr/local/bin/arm-apple-darwin9-gcc
CXX=/usr/local/bin/arm-apple-darwin9-g++
This command tells make to use your new iPhone toolchain, rather than your
system's toolchain you used earlier. Type make clean at the command line, and
the make program runs the clean rule at the bottom, which deletes the executable
file and object file produced earlier by the previous version of the makefile.
Now you can type make, and the new toolchain is invoked, rather than the system
toolchain. This produces a HelloWorld.o object file and HelloWorld executable file for
the iPhone. Copy it to your device to see whether your toolchain really works.
Connect your device to your WiFi network, find out its IP address in the Settings
application and send the HelloWorld executable file to it with a command like the
following (substitute IPHONE_IP with the IP address for your device).
ssh root@IPHONE_IP
When you've logged in, you're at the root user prompt on the iPhone.
./HelloWorld
And I bet you're disappointed by the "Killed" output in the console. What happened is
that the iPhone executable loader expects all executables to be signed. The iPhone
Dev Team did manage to remove nearly all restrictions from the iPhone OS V2.0,
but they didn't want to mess too much with the executable loader. All is not lost: You
can use the ldid command from the Linker Identity Editor utility you installed with
Cydia earlier. The ldid command produces a bogus executable signature to fool
the executable loader.
ldid -S HelloWorld
./HelloWorld
This time, it works, and the crowd roars its approval. You've successfully run code
on your device that you wrote and compiled yourself just minutes ago. You reach the
only logical conclusion a budding iPhone programmer can reach at this point: Let's
put a GUI on it!
Open the new makefile in Eclipse, shown in Listing 3, and examine it.
CC=/usr/local/bin/arm-apple-darwin9-gcc
CXX=/usr/local/bin/arm-apple-darwin9-g++
LD=$(CC)
CFLAGS=-I/usr/local/lib/gcc/arm-apple-darwin9/4.2.1/include \
-isysroot /usr/local/iphone-sysroot
This makefile version adds CFLAGS and LDFLAGS, which tell the compiler and linker
where to find its include and library files. Notice the -framework linker parameters.
These tell the linker to use the frameworks you grabbed from the iPhone firmware
when preparing your iPhone toolchain.
The CC compilation rule has also changed. You're no longer compiling .c files to .o
files; rather, you now concern yourself with .m files. As you probably inferred when I
said that HelloWorld.m substitutes HelloWorld.c, .m (which stands for module) is the
source file for Objective-C programs.
There is an extra rule for something called HelloWorld.app. From looking at the
commands below the rule, it seems to be a folder in which you pile the executable
and some other files, like Info.plist. Listing 4 shows that file.
Listing 4. Info.plist
The Info.plist file is used by the iPhone dashboard UI to figure out what the name of
the executable is and what to call the icon on the touchscreen. The Info.plist is what
turns your HelloWorld.app from just a folder with some stuff in it into an actual
iPhone application bundle. Note that Info.plist has an uppercase I in its name: The
iPhone dashboard is picky and expects the files in the bundle to be named precisely.
The bundle also contains two graphics files: Default.png and icon.png. The iPhone
dashboard uses icon.png as the icon for your program on the dashboard.
Default.png is used to display a dummy graphic on the screen while the user waits
for your executable to load and draw its UI.
Note: The icon.png file name must be all lowercase or it won't be displayed.
Likewise, Default.png must have an uppercase D or it won't be displayed at
application start-up.
Now, move on to the real meat of the application: the Objective-C code that makes it
all happen.
Listing 5. HelloWorld.m
//
// HelloWorldApp.h
// HelloWorld
//
// Created by PJ Cabrera on 08/18/2008.
// Copyright PJ Cabrera 2008. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "HelloWorldApp.h"
int main(int argc, char *argv[]) {
// This autorelease pool is managed by the UI's event dispatcher. It autoreleases
// any allocated objects that fall out of scope. The iPhone's implementation of
// Objective-C 2.0 does not have garbage collection yet, but autorelease pools and
// proper release of allocated objects is still a good practice.
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// This is where UI execution gets started. This instantiates the UIApplication
// subclass and UIApplicationDelegate subclass specified as string parameters.
// The name of an UIApplication subclass can be passed as both UIApplication and
// UIApplicationDelegate.
UIApplicationMain(argc, argv, @"HelloWorldApp", @"HelloWorldApp");
// Force release of the autorelease pool and all objects still allocated.
[pool release];
return 0;
It actually doesn't look terribly different from C. Foundation and UIKit are the two
Objective-C frameworks you will use the most in the Cocoa Touch platform.
Foundation is where strings, lists, and base object-oriented hierarchies are defined
in Cocoa and Cocoa Touch. UIKit defines quite a lot of the UI elements in an iPhone
application.
Listing 6. HelloWorldApp.m
//
// HelloWorldApp.m
// HelloWorld
//
// Created by PJ Cabrera on 08/18/2008.
// Copyright PJ Cabrera 2008. All rights reserved.
//
#import "HelloWorldApp.h"
@implementation HelloWorldApp
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Create a "full-screen" window to hold the UI.
window = [[UIWindow alloc] initWithContentRect:
[UIHardware fullScreenApplicationContentRect] ];
// Create a view to hold the window contents.
contentView = [[UIView alloc] initWithFrame: CGRectMake(0.0f, 0.0f, 320.0f, 480.0f)];
// Create a navigation bar for the top of the view, with two buttons.
// The buttons do not do anything in this example.
nav = [[UINavigationBar alloc] initWithFrame: CGRectMake(0.0f, 0.0f, 320.0f, 48.0f)];
[nav pushNavigationItem:[[UINavigationItem alloc] initWithTitle:@"Hello World"]];
[nav showButtonsWithLeftTitle: @"Left" rightTitle: @"Right"];
[nav setBarStyle: 0];
[contentView addSubview: nav];
// Create a text view, this is a basic text editor, with incorporated keyboard.
text = [[UITextView alloc] initWithFrame: CGRectMake(0.0f, 48.0f, 320.0f, 480.0f)];
[text setText: [[NSString alloc]
initWithString: @"Hello World\nCocoa Touch Application"]];
[contentView addSubview: text];
// UIWindow con only hold one view, the contentView. The contentView can hold many
// navigation controllers, which control the different views in your application.
window.contentView = contentView;
// These three instructions effectively show the window.
[window orderFront: self];
[window makeKey: self];
[window _setHidden: NO];
}
- (void)dealloc {
// Release the UI elements as they were allocated
[text release];
[nav release];
[contentView release];
[window release];
// And don't forget to call the parent class dealloc
[super dealloc];
}
@end
Next, it allocates and initializes a UIView instance, which holds all the other screen
elements. There is a navigation bar with two buttons called Left and Right that in
this example are just for show. There is also a big UITextView instance with the
text "Hello, World" and "Cocoa Touch Application" on two separate lines. Finally, set
this view as the main view for your window, and set the window to receive input and
be visible.
If you run make and everything goes on without a hitch, make will have created a
HelloWorld.app folder and copied into it your Info.plist file, the icon.png, and
Default.png images, and your HelloWorld executable file. Copy that folder to your
device. As before, replace your iPhone's IP address for IPHONE_IP in the
commands below.
When you log in to the device, sign the executable to make it runnable.
ldid -S /Applications/HelloWorld.app/HelloWorld
After you've resprung the dashboard, your HelloWorld application shows among the
other icons. Touch it to launch it and behold: a navigation bar at the top with two
buttons named Left and Right, and a large text view with the phrases, "Hello World"
and "Cocoa Touch Application," on two separate lines. And the big surprise: Touch
the text area and a keyboard pops up from the bottom of the screen to let you type.
The keyboard comes "for free" when you create a text area. You didn't have to write
code to enable it.
Section 8. Summary
Using Eclipse to program applications for the iPhone is not without issues.
Objective-C is not supported by the refactoring tools, it is not easy to set up remote
debugging at the moment (even though GDB supports Objective-C debugging), and
third-party plug-ins like Color Editor have to be installed to obtain syntax highlighting
of Objective-C code. I could have spent more time setting up Eclipse CDT to allow
compilation within Eclipse rather than using make from the command line. But then,
this would have turned into an Eclipse CDT tutorial instead of a Cocoa Touch
tutorial.
I hope this tutorial gets you started. Programming the iPhone can be lots of fun.
Resources
Learn
• Stop by the iPhone DevCenter to learn about the Apple iPhone SDK.
• The official iPhone Dev Team information portal, containing "accurate, useful
and concise information portal about Dev Team progress."
• For more information about jailbreaking your iPhone using WinPwn, read "How
to Unlock/Jailbreak Your 2.0 EDGE iPhone with WinPwn on Windows" from
iClarified.
• For information about jailbreaking your iPhone 3G using WinPwn, read "How to
Jailbreak Your 2.0 3G iPhone with WinPwn on Windows" from iClarified.
• For information about jailbreaking your iPhone using Pwnage, read "How to
Unlock/Jailbreak Your 2.0 EDGE iPhone with Pwnage Tool on Mac OS X" from
iClarified.
• Read the developerworks article "Develop iPhone Web applications with
Eclipse" to learn how to create iPhone Web sites using Eclipse, Aptana's
iPhone Development plug-in, and the iUi framework.
• Read the developerworks tutorial "Debug iPhone Web applications with Eclipse"
to learn how to debug Asynchronous JavaScript + XML (Ajax) Web applications
using Eclipse, Aptana's iPhone Development plug-in, Aptana's Firefox
JavaScript debugger, and Firebug.
• For information on jailbreaking your iPhone 3G using Pwnage, read "How to
Jailbreak Your 2.0 3G iPhone with Pwnage Tool on Mac OS X" from iClarified.
• Check out CNet's video explanation of jailbreaking the iPhone.
• For information about jailbreaking your iPhone using QuickPwn, read "How to
Jailbreak Your 2.0 iPhone with QuickPwn on Windows" from iClarified.
• See the official information page for Xpwn.
• Check out the "Recommended Eclipse reading list."
• Browse all the Eclipse content on developerWorks.
• New to Eclipse? Read the developerWorks article "Get started with Eclipse
Platform" to learn its origin and architecture, and how to extend Eclipse with
plug-ins.
• Expand your Eclipse skills by checking out IBM developerWorks' Eclipse project
resources.
• To listen to interesting interviews and discussions for software developers,
check out developerWorks podcasts.
• The Eclipse newsgroups has many resources for people interested in using and
extending Eclipse.
• Participate in developerWorks blogs and get involved in the developerWorks
community.