Programming AmigaOS in C

2. Opening a Library

To access shared libraries, you need to open them first before you can use the functions provided. This is done using the OpenLibrary() function which is an exec.library function.
The exec.library is the only library that is always open and is open as soon as AmigaOS is loaded. To open a library you need to provide the full name of the library and the minimum version
of the library (starting from 30 upwards), if you do not care which version then just use 0. A minimum version may be required if using a later version of AmigaOS and need to make sure that
that version of AmigaOS is running before starting the application. When a library is opened, it will return a pointer to a Library structure or a Base structure specific to that library otherwise
it will return a NULL value.

Example, Opening the Intuition Library

/* Include appropiate header*/
#include <proto/intuition.h>

/* First declare a pointer to the IntuitionBase structure */
struct IntuitionBase *IntuitionBase;

/* Now open the library for Intuition */
IntuitionBase = (struct IntuitionBase *)OpenLibrary("intuition.library", 39);

Note, that the result of OpenLibrary has been cast to type of IntuitionBase, as by default, it will return a structure of type Library. You would normally test to see if that library is opened before trying
to use of the functions and exit gracefully.
e.g.

if (IntuitionBase) {
/* some code here */
}
else {

printf("Failed to open Intuition library.\n");
exit(5);
}

For AmigaOS 4, Opening a library is slightly different, instead of using a specific Library base structure, they all use the Library structure and to open a library use IExec->OpenLibrary() function instead, for example:

struct Library *IntuitionBase;

IntuitionBase = IExec->OpenLibrary("intuition.library", 0L);

If you wish to compile your code for OS 3.x and OS 4.0 then use the #ifdef, #else and #endif feature.

e.g.

#ifdef OS3x
  IntuitionBase = (struct IntuitionBase *)OpenLibrary("intuition.library", 39);
#else
  IntuitionBase = IExec->OpenLibrary("intuition.library", 0L);
#endif

3. Opening Libraries automatically

Most Amiga C/C++ Compilers can open and close the libraries for you as part of the startup code. As long as you have the protos included in the headers and the appropiate compiler options specified, the compiler will take care of opening any used libraries for you. SAS/C, Storm C, GCC and VBCC can do this. For GCC use either the noixemul or auto options.

4. Closing a Library

To close a library, use the CloseLibrary() function and provide the pointer to the Library or Base structure which was returned in the OpenLibrary(). It is normal practice to test that the library was opened before trying to close it.
For example,

if (IntuitionBase) CloseLibrary( (struct IntuitionBase *)IntuitionBase);

Next Page