Developing applications for the iPad


If you’ve not been living in a cave with Osama Bin Laden for the past six months you’d be aware that Apples new creation the “iPad” is out & selling like hot cakes. As soon as the iPad was announced Apple worshipers started flocking to Apple Stores worldwide lining up to get their hands onto the Steve Jobs latest revelation. It’s not new for Steve Jobs to carve out a niche for his products and stun the aesthetes and geeks alike. Steve Jobs is a visionary who has transcended computing to the heights unimaginable before. iPod, iPhone & iPad are not just bare computing devices anymore they’ve become a part of our contemporary culture.

According to http://www.geek.com Apple has sold more than 3 million iPads since its launch at a flashing rate of almost one iPad every other second and industry experts say the trend is most likely to continue. This 3 million plus & growing consumer base represents a very handsome opportunity for the developers to tap into.

If you’ve been developing for the iPhone/iPod touch you’re in luck, iPad uses the same architecture, same operating system, same set of development tools & same application framework. Hence easing the life of developers but still there are a few subtle difference that one needs consider when developing for iPad.

Support for Screen Orientations

First and foremost thing that developers should consider is the support for all screen orientations. This behavior differs slightly from the iPhone, where running in both portrait and landscape modes is not required.

New UI Considerations

iPad changes the way user interacts with your application. iPad have a larger screen real estate & lends itself to a different set of behaviors for navigating information. On the other hand iPhone apps tend to be more navbar style applications where you dig in level by level to access the required information. This type of applications suits iPhone & iPod touch because screen size is very limited. For managing information density and presentation on larger screen two new concepts are introduced in the iPad SDK namely Popover Controller & Split View Controller.

Popover Controller

UIPopoverController is not a UIViewController, instead it is used to host a content view controller, that content view controller has a view that it manages and this content view controller gets the viewWillAppear: viewDidAppear etc delegate calls. UIPopoverController is usually controlled by some other object that can be another view controller or the applications delegate to manage its lifetime.

You create UIPopupViewController by calling

-   (id)initWithContentViewController:(UIViewController *)viewController;

The view controller provided becomes the content view controller for the UIPopoverController.

You present the UIPopoverController using

- (void)presentPopoverFromRect:(CGRect)rect inView:(UIView *)view permittedArrowDirections:(UIPopoverArrowDirection)arrowDirections animated:(BOOL)animated;

allowing you to present a popover from a rect in a particular view. “arrowDirections” is a bitfield which specifies what arrow directions are allowed when laying out the popover; for most uses, “UIPopoverArrowDirectionAny” is sufficient. Another convenience method that can be used for presenting UIPopover is

- (void)presentPopoverFromRect:(CGRect)rect inView:(UIView *)view permittedArrowDirections:(UIPopoverArrowDirection)arrowDirections animated:(BOOL)animated;

allowing you to present it from a “UIBarButtonItem” instance. “arrowDirection” is limited to UIPopoverArrowDirectionUp/Down only.

To dismiss it you call

- (void)dismissPopoverAnimated:(BOOL)animated;

The delegate methods for “should” and “did” dismiss are not called when the popover is dismissed in this way.

Split View Controller

UISplitViewController is a full screen view element, which is itself a UIViewController sub class. It has a delegate that informs it about the events that happen. Split views are a way to present two custom views side-by-side. They are a good supplement for navigation-based interfaces and other types of master-detail interfaces.

You usually create them in nibs but they can also be created programmatically

UISplitViewController *svc = [[UISplitViewController alloc] init];

There are a couple of delegate methods that you can look up in the UISplitViewController.h header file or the official documentation to get a better understanding.

SplitViewController

SplitViewController

Tabs

Tabs can appear on the top or at the bottom of the screen on the iPad. You can also put tabs in the top of your Popover views.

Modal Presentation

Views that are presented modally now can be configured to cover only a part or the entire window.

Custom Input Views

Now, you can associate an input view with any custom views you create. You are not just limited to the default keyboards provided with the UIKit.

PDF Generation

Starting from iOS3.2 now you can create PDF files in your home directory.

Document Interaction Controller

You can use UIDocumentInteractionController class to preview files, copy their contents to the pasteboard, or pass them to another application for opening. This is feature is also present in iOS4.

New Gesture Recognizers

iPad introduced support for detecting gestures in a uniform manner. Gesture recognizers simplify the interface for detecting swipe, pinch, and rotation gestures, among others. This functionality is also present in iOS4.

Multimedia

If you create video content areas, you do not have to display the video across the entire screen, and you can restrict video to only a small portion or area of the screen. This functionality can be used to combine the user experience with multiple multimedia functionality.

Universal Apps

You can also use XCode to generate universal binaries that run on both the iPhone & iPad check out the official documentation on how to do it. If your code needs to follow a different path depending on the underlying device type, you can use the userInterfaceIdiom property of UIDevice to determine which path to take. Something like this

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)

{

// The device is an iPad running iPhone 3.2 or later.

//create PopoverViewController etc… iPad specific.

}

else

{

// The device is an iPhone or iPod touch.

// Create Navigation Bar etc… iPhone specific

}

Hello Android

The year was 2007 the launch of Apples iPhone changed everything, revolutionizing the very niche of smart phones. Phones weren’t phones anymore they were compact mobile computing devices pushed to next level. Soon pretty much everybody started to jump on the smart phone bandwagon, initially following the path paved by Apple & then eventually challenging the very king of the jungle. The biggest challenger & threat to iPhone appeared to be the Android platform.

History of Android

In July 2005 Google acquired a new small start-up company known as Android Inc. A little was known about the company back then apart from that it developed software for mobile phones.

In 2007 Google joined hands with around 70 other industry leaders to form an alliance, which came to be known as Open Handset Alliance to develop a next generation mobile computing platform. The alliance vowed to come together & accelerate innovation in mobile computing to develop a richer, less expensive & open platform, the result of which is just sheer brilliance.

An early look SDK was released in November 2007 & in September 2008 first Android phone, T-Mobiles G1 was launched & subsequently Google release the source code of Android platform under Apache’s open source license.

Today around hundred Android mobile phones exist in the market.

Architecture

Android is an open software platform, which includes a complete software stack from the operating system to the middleware & up through the applications.

At its core Android runs a modified version of Linux kernel specifically the 2.6.* kernel. The diagram below from the Android website shows us how the android platform is implemented. Linux acts as a HAL (hardware abstraction layer) providing memory management, process management, networking etc amongst other things.

The next level up is the native libraries which are basically native C/C++ libraries providing a plethora of functionalities, from SSL implementation, SQLite, Webkit to the surface management. The C library is based on BSD(Berkeley Software Distribution) & is fine tuned for embedded Linux-based devices. The WebKit library is the same library that powers Google Chrome & Apple’s Safari & is used on Android to provide browser support. Font type is responsible for font support. SQLite is responsible for in memory relational management of data. 2D support is present in Skia & 3D graphics support is based on OpenGL ES. Android provides a software implementation of OpenGL ES, which is hardware accelerate-able if the device has a graphics chip.

Adjacent to these libraries lies the Android runtime, which basically consists of Core Android Java libraries sitting on top of Dalvik Virtual Machine.

Rather then using the traditional Java virtual machine Google implemented its own virtual machine the Dalvik VM. Dalvik is the name of the town in Iceland from where the chief programmer of the VM belongs.  Dalvik is highly optimized for the mobile devices with better Garbage collection & lower memory footprint. The Dalvik VM takes the generated java class files & combines them into one or more Dalvik Executable .dex files. Dalvik VM uses a different kind of assembly code generation, in which it uses the registers as the primary source of data storage instead of the stack hence reducing the instructions up to 30 percent on the ARM processors. It should be noted that you cannot directly run the java bytecode generated elsewhere on the Dalvik VM you will have to convert the source code to .dex files to run it on Android.

The Java core Libraries includes all the collection classes, utilities, I/O etc that you have been using in the J2SE implementation of Java apart from Swing & other AWT classes.

Just below the applications lie the Application Framework, it is the toolkit that almost all Android applications use. Activity manager manages the lifecycle of the applications. Package manager keeps track of all applications that have been installed on the device. The window manager manages windows & is basically a wrapper on top of lower level services provided by the surface manager. Telephony manager provides support for telephony related features. Content manager allows for the applications to share their data with other applications. Resource manager handles all the resources related to your app, anything that isn’t code is handled by resource manager. View system consists of UI elements which also handles things like event dispatching layout, drawing etc. Location manager is used to provide geographic related data to the device. For example you can register an intent with the location manager to notify you when you get close to a point. Notification manager allows any application to put notification onto the status bar to alert the user about any interesting event. XMPP allows application to send device-to-device data messages to other android users.

The Android UI

The Android UI framework is in par with the cutting edge UI frameworks available today like JavaFX or Microsoft Silverlight. The entire interface even the animations can be declared in the XML files. Screens or windows in Android are referred to as activities that can consist of multiple views. Views are basic building blocks in Android. A View occupies a rectangular area on the screen and is responsible for drawing and event handling. View is the base class for widgets, which are used to create interactive UI components (buttons, text fields, etc.).

Android Application Foundations

Activity

Activity represents a single screen in your application; it contains one or more views.

Intent

Intent is an intention to so some work like for example an applications intent to dial a phone number, to launch an activity or to start a service. Intents are not always initiated by your application, they can used by system to notify your application that a certain event has occurred like for example arrival of a text message or a phone call.

Service

Services in Android are background tasks that can run potentially for longer periods. There are two types of services on Android local & remote. Local services are only accessible to the application that is hosting the service & remote services are meant to be used by other applications running on the device. An example of service could be a music player, which keeps on running in the background.

Content Provider

Enables apps to share data across the apps on the device. Like for example if you want to access the address book on the device you would ask content provider for it.

With all the info under our belt let’s quickly develop a small Hello Android application. Follow the instructions below stepwise

  • Download the eclipse IDE from http://www.eclipse.org/downloads/. Unzip & install it on your system.
  • Download a copy of Android SDK from http://developer.android.com/sdk/index.html. Unzip it & place it in your home directory or where ever you like.
  • Add the location of your SDK directory location to your PATH. On Linux I had to edit ~/.bash.rc by appending this text “export PATH={PATH}:~/android-sdk-linux_86/tools”. Just enter command vi ~/.bashrc, scroll to the end & paste the export statement above by first pressing “i” to enter the insert mode press escape to exit insert mode & then write “:wq” to write ie save & quit the vi editor.
  • Fire up Eclipse go to help menu click on Software Updates add a new site in Available software’s https://dl-ssl.google.com/android/eclipse/
  • Restart Eclipse.
  • Go to window preferences & in Android preferences add the location of your SDK.
  • Use the Android SDK and AVD Manager, included in the SDK starter package, to add one or more Android platforms. Use this page as a reference if you’re unsure http://developer.android.com/sdk/adding-components.html.
  • After that go to File menu -> New and click on the Android project.

  • In the following modal window enter the name of project HelloAndroid.
  • In build target select Android 2.2.
  • In application name texbox write HelloAndroidApp
  • In package name write com.semanticnotion.android or whatever you like
  • Click the create activity checkbox and write HelloActivity in the textbox.
  • Set the minimum SDk version to 5 and click finished.
  • You’ll be presented with a bare minimum of Androids application skeleton. Go to the source folder in Eclipse for the project to edit the HelloActivity.java & modify the onCreate() method as follows:

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

TextView tv = new TextView(this);tv.setText("Hello Android");

setContentView(tv);

}

  • Also add this import statement on the top

import android.widget.TextView;

  • Then go to Run -> Run Configurations. On the Configurations dialog box insert a new configuration name it RunHelloAndroid.
  • Click browse & select HelloAndroid project.
  • Under launch action select com.semanticnotion.android.HelloActivity from the drop down list.
  • Click Apply & then Run.

And voila!! If everything goes well you’ll see the emulator with your app running on it.

Apples iOS4 update What’s in it for the developers

Last week at Apples World Wide Developer Conference Steve Jobs unveiled iPhone OS’s yearly major upgrade, introducing a plethora of new functionality. In this post we will try to touch the tip of iceberg in terms of what iOS4 has to offer to the developers.

The first thing you’ll notice about iPhoneOS is that it has been renamed to iOS basically because now it runs on iPads, iPhones & iPod touches & iOS is somewhat a generic name.

Below is the description of new features in the iOS from the developer’s point of view.

Multitasking

The first and foremost thing that catches the attention of developers is the ability of iOS4 to multitask. Multitasking is not a new feature in mobile computing, Palm’s WebOS, Google’s Android & even Microsoft’s Windows Mobile have multi-tasking capabilities. Multitasking application lifecycle is a little different than the traditional application lifecycle that we were used to in Cocoa touch. Apples multitasking implementation is somewhat similar to that of Google’s on the Android platform. Which is in-fact not true multitasking just a mere illusion of multitasking.

When the user wants to switch to another application the state of application is saved or frozen in the memory and when the user gets back to the application the state of application is restored giving an illusion that application was running all along.

When the application is inactive it is barred from any processing except if the application has registered as one of the following

  • Location (GPS related)
  • Audio
  • VoIP (Voice over IP)

This is how application state is specified in the UIApplication.h header file

typedef enum {

UIApplicationStateActive,

UIApplicationStateInactive,

UIApplicationStateInBackground

} UIApplicationState;

Illustrating that we have three application states on the iOS4.

  • Active
  • Inactive
  • In Background

When the application is launched we will receive the usual message from the app delegate

- (void)applicationDidFinishLaunching:(UIApplication *)application

didfinishLaunchingWithOptions(NSDictionary *)launchOptions

In addition to this we will now also receive this message

-   (void)applicationDidBecomeActive:(UIApplication *)application

When going to the background we will receive these messages

- (void)applicationWillResignActive:(UIApplication *)application

- (void)applicationDidEnterBackground:(UIApplication *)application

When in background there are no guarantees that the app will remain in the memory for the entire eternity. If there is a OOM(Out Of Memory) call the runtime will kill our application & free some memory.

When our application comes back to foreground these two methods will be called by the app delegate.

- (void)applicationWillEnterForeground:(UIApplication *)application

- (void)applicationDidBecomeActive:(UIApplication *)application

We can implement our logic in these two delegates; like connecting to the server again or whatever the logic of our application demands.

iOS4 also gives us the functionality to ask for a little more time for processing when the application is being suspended so that we can save state or finish the job for that matter before getting suspended. These are the two calls we can use to tailor our app to our requirements.

-   (UIBackgroundTaskIdentifier)beginBackgroundTaskWithExpirationHandler: (void(^)(void))handler;

-   (void)endBackgroundTask:(UIBackgroundTaskIdentifier)identifier;

*Notice the weird looking syntax (void(^)(void)), this is known as a block & is a recent addition to the C, C++, Objective C & objective C++ by Apple & is abundantly used in many Foundation classes so understanding it is very crucial, more on it later.

Local Notifications

A new feature in iOS4 is of local notification system, this feature somewhat mimics the Apples Push Notification System but is local to the device. Any application can register for notifications locally on the device & the device can then send periodic updates as specified or can change the application badge or do all of the stuff that was possible with Push Notification System. For more information on Local Notification be sure to check out the UILocalNotification.h header file.

UIAutomation

UIAutomation is a new framework that Apple has introduced with the iOS4 SDK. Now you can write Javascript based scripts to automate user testing & check your application rigorously. You can run your scripts along with all the performance tracking systems included in the SDK like Instruments or Shark.

Event Kit

Enables the developers to access the calendar of the user on the device, so that the developer can create, edit, remove & search events on the calendar locally & or any online calendars users are using. Developers will also be able to record change notifications for the events on the calendar.

iAd

iAd is Apples advertising framework, developers can use iAds for loading & presenting ads. Apple also enables developers to respond to the events in ads. One plus point of iAd is that when you tap on the ad in the application, the application will not exit to show you the ad in Safari, you will remain in the application & you can close the ad anytime you want. This is one big convenience when compared with other ad offering frameworks like Google’s Ad-Mob.

Game Center

Is a social networking gamming system something like OpenFeint. Now you can view achievements, compare them with your friends, view leader boards, find new games etc all of the stuff which you were able to do with OpenFeint is now possible with Game Center.

Core Motion

In addition to the accelerometer Apple has added the gyroscope to the iPhone 4. Now you can use the API in the Core Motion to take advantage of gyroscope & make your applications more interactive.

Core Foundation & Foundation additions

CF & NSFoundation has been brought to the snow leopard equivalence in iOS4, which includes the inclusion of Blocks & Regular Expressions to name a few.

Blocks

Here is a small introduction to Blocks to get your feet wet.

Blocks are self-contained units of work; they are similar to but far more powerful than traditional function pointers. Blocks are objects & they respond to NSObject methods. Here is a small example on blocks to get you started:-

Declaring a block variable:

void (^my_block)(void)); //first void is return type (^my_block) is the block declaration & the other void is the argument in the argument list.
Assigning a block object to it:

my_block = ^(void){ printf("hello world\n"); };
Invoking it:

my_block(); // prints “hello world\n”
Accepting a block as an argument:

- (void)doSomething:(void (^)(void))block;
Using that method with an inline block:

[obj doSomeThing:^(void){ printf("block was called"); }];

Google’s Go Programming Language

Google’s New Programming Language GO

Introduction.

In this blog post we will go through the installation of the Go programming language tool-chain on Linux & most probably talk about the basic programming constructs of this language.

I am using an Intel Core 2 Duo processor and Linux flavor is Ubuntu 9.10 code named Karmic Koala.

The official installation procedure can be found at http://golang.org/doc/install.html. We will be following the same procedure but I will be explaining few of the steps in between so that you don’t get lost.

Step 1. Setting Environment Variables

First thing we need to do is to set the environment variables in .bashrc in your home directory. You can read more about bash & .bashrc at http://en.wikipedia.org/wiki/Bash#Startup_scripts.

On your Linux desktop go to the Applications menu → Accessories → Terminal. This will bring up the terminal. Type “cd ~” & hit enter to make sure you are in your home directory.

Now type gedit .bashrc in the terminal.

This will open up the .bashrc file in gedit, scroll down to the end add the following text

# Environment variables for Go programming language.

export GOROOT=$HOME/go

export GOOS=linux

export GOARCH=386

export GOBIN=$HOME/bin

Save file & close the document. Type exit in the terminal to exit. Once again go back to the application menu and click on the terminal by following the route specified above.

Type env | grep ‘^GO’ to check environment variables are set correctly.

If everything went well you will see something like this

click to enlarge

Installing Mercurial

Once you the environment variables are set correctly type

sudo apt-get install mercurial

The package if not installed will be downloaded & installed or upgraded depending upon your system.

Screenshot

click to enlarge

You can read more about mercurial here: http://en.wikipedia.org/wiki/Mercurial

Checking Out From The Repositories

Once mercurial is installed type the following command on the terminal to checkout the latest code from repositories

hg clone -r release https://go.googlecode.com/hg/ $GOROOT

Wait for a while until it gets downloaded

Installing Other Required Components

On getting the prompt back type

sudo apt-get install bison gcc libc6-dev ed

If the above-mentioned programs are not installed on your system they will be downloaded and installed.

Installing Go

Once you get the prompt back & above mentioned programs are successfully installed on your system, type:

cd $GOROOT/src

And then enter the following command

./all.bash

Installation process will begin & if all goes well you will see screen like this.

Screenshot-2

click to enlarge

Congratulations you have successfully installed the Go language tool-chain, now its time to get our hands dirty with a little programming.

Hello World in Go

Now type:

cd ~

to go to the home directory now create a new folder by typing

mkdir google-go

type:

cd google-go

to go to the newly created directory.

Now type:

Gedit

& hit enter

Enter the following code in gedit.

Example 1

package main

import fmt “fmt”

func main(){

fmt.Printf(“Hello World from Go programming language\n”)

}

That’s it, save the document as hello.go and exit the gedit.

On the terminal type:

8g hello.g

to compile the source. If all goes well you’ll get to the prompt with anything showing.

Now type 8l hello.8 (thats character ‘l’ after 8 not numeric 1), this command will link the required libraries “fmt “ in our case which imported in our program.

And to run the program type ./8.out

Congratulations you have compiled your first program in Google’s new programming language Go. Be proud of yourself.

Try changing this program use different language constructs. Below is the yet again a simple program which will get you started. I cannot go over every language construct so feel free to visit the official Go website. You’ll grasp the concepts very quickly if you have any prior programming experience.

Example 2

package main

import fmt “fmt”

func main(){

var i int = 1;

var stng string;

var j [10]int;

stng = “A string”;

fmt.Printf(“The String contains : %s, integer contains : %d, and array %i \n”, stng , i, j);

for k := 0; k<10; k++{

fmt.Printf(“%d Checking for loop\n”, k);

}

}

You should have noticed that Go is a C based language & C/C++ programmer will have no trouble using this language.

Below is one hour Google Tech Talk video hope you will enjoy it.

You can always visit the official website http://golang.org/ to learn more.

Philosophy of Make

Introduction.

In this blog post I will try to explain to you the anatomy of a typical make file, as most of the new comers to Unix/Linux arena often find it difficult comprehend the philosophy behind the make & they often do get imitated by its weird looking syntax and structure. We’ll first describe why a make is needed and then I will highlight the basic structure and syntax of a make file and will then we will wrap up the post by presenting some examples to make your concepts clear.

The case for make

Make is a tool that is used to control the build process of your software.

Make automates what is built, how it gets built, when it gets built etc. A makefile is a place where you store all of your commands to build the software.

Similar concept exists in the Java world in shape of Ant and more recently Maven that even provide more functionality and flexibility to compile, test & even deploy your applications through simple xml files.

Suppose you have multiple source files that require long & complex compiler invocations, “make” simplifies this by storing these commands in a single makefile so that they can be managed from a single location. You can also specify which files & directories you want create and delete based upon certain circumstances. Like for example you want all your library files to be compiled into the lib folder of the installation directory. “Make” also makes it easier for other people who want to compile and execute your application; in place of creating huge documentation on how to build your software you can just tell them to run make & it would take care of the rest.

Finally as the final argument in favor of make I think it really speeds up the build process of your application. Make is intelligent enough to recognize which files have changed and thus only builds those files whose components have changed. Plus makefiles also constitute a database of dependency information allowing you to automatically verify that all the files for the build are present.

Anatomy of a MakeFile

A make file is a simple text file containing rules that tell make what to build and how to build it. A makefile consists of number of rules, at its basic the general structure of make looks likes this:-

# Comments use the hash symbol

Target : dependency [dependency] [ … ]

Command 1

Command

Command n

Target is what we are trying to build a binary or an object file. Dependency is a list of one or more files required for the compilation, commands are the steps either compiler invocations or shell scripts required to create the target.

The spaces before commands are TABS & should be used as such, empty spaces would not suffice in their place & you would get the missing separator error. This is the most common problem people new to make get stucked with.

Example of a Make File

edit : main.o kbd.o command.o display.o \

insert.o search.o files.o utils.o

cc -o edit main.o kbd.o command.o display.o \

insert.o search.o files.o utils.o

main.o : main.c defs.h
              cc -c main.c
kbd.o : kbd.c defs.h command.h
              cc -c kbd.c
command.o : command.c defs.h command.h
              cc -c command.c
display.o : display.c defs.h buffer.h
              cc -c display.c
insert.o : insert.c defs.h buffer.h
              cc -c insert.c
search.o : search.c defs.h buffer.h
              cc -c search.c
files.o : files.c defs.h buffer.h command.h
              cc -c files.c
utils.o : utils.c defs.h
              cc -c utils.c
clean :
      rm edit main.o kbd.o command.o display.o \                               
      insert.o search.o files.o utils.o

Two long lines are split into two by using backslash-newline. This make file will create an executable “edit”.

To compile the program simply just type make on the command prompt.

This make file has 10 rules. The first target edit is the default target which is the binary we are trying to create. Edit has eight dependencies from main.o to utils.o, all of these files must exist to create the edit binary. The next line is the command that make executes to actually create the binary. Here make would actually build the executable from all these object files that are named .o.

When make encounters a dependency and it does not exists make executes the command to build it & if the dependency has further dependencies make tries to find them & if they does not exist make tries to build them using the command specified and so likewise make is able to traverse through all of the dependencies if present and build the software smoothly.

Clean target as you can see is the simple command that removes all the object files and as well as the final binary using the rm command.

Phony Targets

A phony target is one that is not really the name of a file. It is just a name for some commands to be executed when you make an explicit request. There are two reasons to use a phony target: to avoid a conflict with a file of the same name, and to improve performance.

Like for example there is a file named clean it would be disregarded by make. Phony targets are defined like this in a make file for example

.PHONY : clean zip

rm abc.o xyz

zip : clean

zip abc.zip *.c *.h Makefile

There are a lot of command line arguments that make can take the following is a short list of useful command options.

-f file                         Read the file name file instead of standard names

-n                         Display the commands make would executes without actually executing them

-s                        Execute silently ie not printing the commands make executes

-w                        print directory names when make changes directory

-r                         disable all of makes built-in rules.

-d                         print lots of debugging information

-k                         keep executing even if one target fails to build.

-jN                        Run N commands in parallel, where n is an non-zero integer.

More exhaustive list can be found at http://www.gnu.org/software/make/manual/make.html#Options-Summary

Variables

To simplify editing and maintenance make allows us to use variables. There are four kinds of variables

  1. User defined variables
  2. Environment variables
  3. Automatic variables and
  4. Pre-defined variables

User-Defined Variables

We define variables using the general form:

VARNAME = value [ … ]

It is a convention to use upper case letters for variables names, to obtain a variables value we just parenthesize the variable and add a dollar sign as a prefix.

There are two kinds of variables in “make” simply expanded variables and recursively expanded variables. Recursively expanded variables as the name suggest expands variables within variables until there are no further variables. For example

HOME_DIR = /home/asad

DEV_DIR = $(HOME-DIR)/development

PROJ_DIR = $(HOME-DIR)$(DEV-DIR)/project

SRC_DIR = $(HOME-DIR)$(DEV-DIR)$(PROJ_DIR)/src

If you use SRC_DIR variable somewhere all of the variables would get expanded.

Simply expanded variables are scanned once where they are defined and all embedded variable references are immediately resolved. Syntax is slightly different

CC := gcc

CC += -g

This would result in gcc –g when resolved.

If you consider using recursively expanded variables for this for example

CC = gcc

CC = $(CC) – g

We would get stuck in an infinite loop as $(CC) would keep on getting resolved to the same expression $(CC) & make would throw an error.

Environment Variables

Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment. $(HOME) variable for example can be used in make to refer to the users home directory.

Automatic Variables

Automatic variables are those variables whose value is evaluated each time a rule is executed, based on target and dependencies of that rule. Automatic variables are used to create pattern rules, patterns are generic instructions on how to compile an arbitrary .c file to its corresponding .o file.

Here is a partial list of automatic variables

$@                        The file name of the target of the rule.

$<                        The name of the first prerequisite/dependency.

$?                        The names of all the prerequisites that are newer than the target, with spaces between them.

$*                         The basename (or stem) of a filename.

$^                        Expands to a space-delimited list of all of a rules depedencies.

$(@D)                        The directory part of targets path name, if named target is in the sub-directory.

$(@F)                        The file part of targets path name, if named target is in the sub-directory.

For an exhaustive list please visit

http://www.gnu.org/software/make/manual/make.html#Automatic-Variables

example:

CFLAGS := -g

CC := gcc

.c .o:

$(CC) $CFLAGS –c $* .c

lock: lock.c

$(CC) $(CFLAGS) $< -o $@

for each filename ending in .c make would create an object file ending with .o, while executing $< would be replace with lock.c similarly target name $@ will be replaced by lock.

Pre-Defined Variables

These are the variables that as the name suggests are predefined by make. A few of them are listed below.

AR                        Archive-maintaining program; default `ar’.

AS                        Program for compiling assembly files; default `as’.

CC                        Program for compiling C programs; default `cc’.

CO                        Program for checking out files from RCS; default `co’.

CXX                        Program for compiling C++ programs; default `g++’.

CO                         Program for extracting a file from RCS; default `co’.

CPP                        Program for running the C preprocessor, with results to standard output; default `$(CC) -E’.

RM                        Command to remove a file; default `rm -f’.

ARFLAGS            Flags to give the archive-maintaining program; default `rv’.

ASFLAGS            Extra flags to give to the assembler (when explicitly invoked on a `.s’ or `.S’ file).

CFLAGS            Extra flags to give to the C compiler.

For an exhaustive list please see

http://www.gnu.org/software/make/manual/make.html#Implicit-Variables

Conditional Statements

Conditional expressions can be applied to a make file so that parts of make file execute or not based on certain conditions. Generic syntax is as follows

conditional-directive

text-if-true

else

text-if-false

endif

The following example of a conditional tells make to use one set of libraries if the CC variable is `gcc’, and a different set of libraries otherwise. It works by controlling which of two command lines will be used as the command for a rule. The result is that `CC=gcc’ as an argument to make changes not only which compiler is used but also which libraries are linked.

libs_for_gcc = -lgnu

normal_libs =

foo: $(objects)

ifeq ($(CC),gcc)

$(CC) -o foo $(objects) $(libs_for_gcc)

else

$(CC) -o foo $(objects) $(normal_libs)

endif

This conditional uses three directives: one ifeq, one else and one endif.

Last Example

In the last example I would like to show you how to create install, dist and uninstall targets that you can most probably use while distributing your applications.

Hello: hello.c

install : hello

install $< $(HOME)

.PHONY : dist unistall

dist :

$(RM) hello *.o core

tar czvf hello.tar.gz hello.c Makefile

uninstall:

$(RM) $(HOME)/hello

and you can use make install, make dist & make uninstall commands for respective functions.

With this I think we should wrap up our tutorial on make. This is not a fully exhaustive tutorial but it would place you on the right grounds & will get you started with make hopefully. If you have any questions please don’t hesitate to ask and If you want to know more about specific details & I don’t impress you much you can always access the online documentation at http://www.gnu.org/software/make/manual/.

Developing iPhone applications on Linux.

Introduction

As we all know that Apple has limited the native application development of iPhone/Cocoa touch to only the MAC OS X & its IDE Xcode, which consequently leave out a huge number of developers out of the thrill. In this tutorial/article we will try to explore how we can use our beloved Linux machine to develop applications for iPhone/Cocoa touch platform.

We will follow a step by step tutorial to install tool-chain for the iPhone/Cocoa Touch and in the end I will also provide elaboration on how to use our very own Eclipse IDE for code editing features for objective C.

Basic Linux acquaintance and a know how of C language is a pre-requisite.

You will be needing an iPhone, a Linux machine, a wifi connection & a little patience to get it done but I can guarantee you once you have done it you would feel like King Arthur, assuming he always felt good.

I will be using Ubuntu 9.04 Jaunty for the sake of our example.


Jail Breaking

At its core MAC OS X is based on Darwin which integrates a couple of fascinating technologies, most importantly XNU kernel a Mach 3.0 based microkernel and operating-system services based on 4.4BSD (Berkeley Software Distribution). Darwin forms the core set of components upon which Mac OS X and iPhone OS are based.

Being basically unix in nature Apple employed a popular UNIX technique known as “chroot” to restrict the access of processes to an isolated subset of the file system.

Wikipedia links for the above jargon if you are interested are highlighted below, as I would not go into the irrelevant lengthy details but will give you pointers where the need arises.

http://en.wikipedia.org/wiki/Mach_(kernel)

http://en.wikipedia.org/wiki/Darwin_(operating_system)

http://en.wikipedia.org/wiki/Chrooted

The first thing you will need to do is to jail break your iPhone. Jail breaking your iPhone wont break your iPhone it will just set your phone free from the restrictions Apple has applied on it, let your phone breahthe in some fresh air. There are a lot of tutorials and softwares available to do this so I wont waste my time on this too, just google it and you will be on the right grounds for sure.

You can even search in youtube and will find video tutorials on how to break the chains of your phone.

QuickPwn, XPwn, Pwnage, and WinPwn; are just a few keywords to make your life a little easier & a little better.

Don’t scroll down if you haven’t Jail broken your iPhone yet. If you are having trouble jail breaking your iPhone just drop me a line below in comments I would be eager to help you out.

Post Jail Break

There are a few softwares we need to install on the iPhone to get our work done. Depending upon the method/software used you will have an installer or a Cydia icon on your springboard(that is the desktop of your iPhone if in case you are wondering what SpringBoard is).

Cydia & installer Icons

Cydia & installer Icons

Search and download the following softwares from either cydia or installer from your iPhone.

OpenSSH secure remote shell client and server(openssh) :enables you to transfer your programs to the iPhone and log in to execute commands on the device

The Linker Identity Editor(ldid): sign your code with a bogus key to make the iPhone run it & the Respring(respring) utility to restart the dashboard.

You can use the keywords in the brackets for search.

Once you have installed ssh open terminal app(Goto Applications on the top right corner of your screen → Accessories → Terminal) & type ssh root@[ip address of iphone], terminal will prompt you to enter roots password type alpine which is the default password for the root. Now type passwd and hit enter to change the default password and secure your iPhone. Do the same procedure for the username mobile which also have the default password alpine.

Note you can see the ip address for your iphone using the Settings application on your iphone and going to WiFi.

Installing the tool-chain

Tool-chain can be installed in two ways, one way which we will discuss further is by downloading the source and compiling the source of the tool-chain and if you don’t want to get into the hassle I will provide my pre-compiled version of tool chain so that you can use it off shelf.

Note tool chain refers to compilers, assemblers, linkers, and other tools that work together to build an executable file for a particular platform; if in case you are wondering what tool chain is.

Installing tool-chain from the source

One advantage you will get from downloading and installing from the source is that you will get the latest build for the tool-chain available.

The iPhone tool chain used by Apple for its iPhone SDK is actually based on the open source GCC — the same tool chain used in Linux, Unix & its variants & which off course is open source.

Because of its open source origins, the base source code for the iPhone SDK is available to anyone under GPL.

The following software’s are necessary to build tool chain on Linux: bison, flex, build-essentials, and autoconf packages. You can use the following command to download and install the programs from the repositories.

The process to download and compile tool chain from the source is explained on the web page http://code.google.com/p/iphone-dev/wiki/Building, If you have any problems or errors while following steps read the comments below and if it still doesn’t suffice leave me a comment I will try to help if possible.

Get a copy of the iPhone root file system, make sure your iPhone and linux box both are connected to the same WiFi network, go to networks double click on the iphone device provide user-name and passwords for authentication and then download these two directories /System/Library/Frameworks/ and /user/lib to your /usr/local directory.

Download the tool chain code from the link

extract the .tar file with any file archiving utility of your choice and then run the following command
cd ~/iphone-2.0-toolchain

./make-toolchain

It will take a while and a lot of text would whiz by your screen and after a while if all went right you would get your prompt back.

Congratulations! you have installed your tool-chain for iPhone on Linux.

Now open a text editor or any IDE e.g eclipse or netbeans whatever you like

Continue reading

Follow

Get every new post delivered to your Inbox.