Next: , Up: GNAT and Libraries


18.1 Creating an Ada Library

In the GNAT environment, a library has two components:

In order to use other packages The GNAT Compilation Model requires a certain number of sources to be available to the compiler. The minimal set of sources required includes the specs of all the packages that make up the visible part of the library as well as all the sources upon which they depend. The bodies of all visible generic units must also be provided. Although it is not strictly mandatory, it is recommended that all sources needed to recompile the library be provided, so that the user can make full use of inter-unit inlining and source-level debugging. This can also make the situation easier for users that need to upgrade their compilation toolchain and thus need to recompile the library from sources.

The compiled code can be provided in different ways. The simplest way is to provide directly the set of objects produced by the compiler during the compilation of the library. It is also possible to group the objects into an archive using whatever commands are provided by the operating system. Finally, it is also possible to create a shared library (see option -shared in the GCC manual).

There are various possibilities for compiling the units that make up the library: for example with a Makefile Using the GNU make Utility, or with a conventional script. For simple libraries, it is also possible to create a dummy main program which depends upon all the packages that comprise the interface of the library. This dummy main program can then be given to gnatmake, in order to build all the necessary objects. Here is an example of such a dummy program and the generic commands used to build an archive or a shared library.

     with My_Lib.Service1;
     with My_Lib.Service2;
     with My_Lib.Service3;
     procedure My_Lib_Dummy is
     begin
        null;
     end;
     # compiling the library
     $ gnatmake -c my_lib_dummy.adb
     
     # we don't need the dummy object itself
     $ rm my_lib_dummy.o my_lib_dummy.ali
     
     # create an archive with the remaining objects
     $ ar rc libmy_lib.a *.o
     # some systems may require "ranlib" to be run as well
     
     # or create a shared library
     $ gcc -shared -o libmy_lib.so *.o
     # some systems may require the code to have been compiled with -fPIC
     
     # remove the object files that are now in the library
     $ rm *.o
     
     # Make the ALI files read-only so that gnatmake will not try to
     # regenerate the objects that are in the library
     $ chmod -w *.ali
     

When the objects are grouped in an archive or a shared library, the user needs to specify the desired library at link time, unless a pragma linker_options has been used in one of the sources:

     pragma Linker_Options ("-lmy_lib");

Please note that the library must have a name of the form libxxx.a or libxxx.so in order to be accessed by the directive -lxxx at link time.