Next: 2.2 Linking your app Up: 2 Libraries Previous: 2 Libraries

2.1 Compiling A Library

We start with a very simple example of a library. Our tiny library will contain a single class, called HelloWorld, which has a method to print out a nice string.

The library has only one header file (called HelloWorld.h), which is the following:

#ifndef _HELLOWORLD_H_
#define _HELLOWORLD_H_

#include <Foundation/Foundation.h>

@interface HelloWorld : NSObject
+ (void) printMessage;
@end

#endif /* _HELLOWORLD_H_ */
(This header file quite simply says that HelloWorld is a subclass of NSObject, and implements a single class method printMessage [a class method is what in java would be called a static method]; the #ifdefs are the standard way of protecting a C header file from multiple inclusions).

The source code of our class is in the file HelloWorld.m, and is the following:

#include "HelloWorld.h"

@implementation HelloWorld
+ (void) printMessage 
{
  printf ("Hello World!\n");
} 
@end
(This implements the printMessage class method for the class HelloWorld, and all what this method does is printing out Hello World!.)

To compile our library, we create a GNUmakefile as follows:

include $(GNUSTEP_MAKEFILES)/common.make

LIBRARY_NAME = libHelloWorld
libHelloWorld_HEADER_FILES = HelloWorld.h
libHelloWorld_HEADER_FILES_INSTALL_DIR = HelloWorld
libHelloWorld_OBJC_FILES = HelloWorld.m

include $(GNUSTEP_MAKEFILES)/library.make

The main differences with the GNUmakefile for a tool or an application are that we include library.make instead of tool.make or application.make, and that we set the xxx_HEADER_FILES variable to tell the make system which are the library header files. This is quite important because the header files will be installed with the library when the library is installed.

In order to do things cleanly, each library should install its headers in a different directory, so headers from different libraries don't get mixed and confused; this is why we specify that our header file has to be installed in a HelloWorld directory:

libHelloWorld_HEADER_FILES_INSTALL_DIR = HelloWorld
As a consequence, an application or a tool which needs to use the library will include the header file by using
#include "HelloWorld/HelloWorld.h"
because we have installed it into the HelloWorld directory.

As usual, to compile type make and to install type make install.


Next: 2.2 Linking your app Up: 2 Libraries Previous: 2 Libraries
2010-03-12