Creating a project, from Makefile to static/dynamic libraries in UNIX Creating a project, from Makefile to static/dynamic libraries in UNIX unix unix

Creating a project, from Makefile to static/dynamic libraries in UNIX


Static libraries are usually archived with the ar command. Once you build all of the object files (preferably with the -fPIC switch on GCC), you can run ar like so:

ar -rs archivename.a list.o of.o objects.o

The man page describes the options.

Dynamic libraries are built usually with the -shared switch to gcc or ld and the output file name with a .so extension.

Autotools handles this with the libtool program. I'm not familiar with its use.

Linking against these libraries can be done either by listing the libraries with the -l (ell) switch (such as -lX to link to libX.so) or by specifying them directly with absolute paths (such as adding /usr/lib/libX.so to your command). Static libraries are linked by specifying -static before -l or the appropriate absolute path to the .a archive.


Bare bones Makefile for creating a static library consisting of the code in foo.cpp, bar.cpp:

PROJECT = library.aOBJECTS = foo.o bar.oCFLAGS  = -Wall -pedanticall: $(PROJECT).cpp.o:        g++ -c $(CFLAGS) $<$(PROJECT): $(OBJECTS)        libtool -o $(PROJECT) -static $(OBJECTS)

Bare bones Makefile for an app baz.cpp that static links to library.a:

PROJECT = bazCFLAGS  = -Wall -pedanticOBJECTS = baz.oall: $(PROJECT).cpp.o:        g++ -c $(CFLAGS) $<$(PROJECT): $(OBJECTS) library.a        g++ $(OBJECTS) -L. -llibrary -o $(PROJECT)

Dynamic library left, ahem, as an exercise to the reader.


Answer 1: To create a static library from source files foo.c and bar.c, do this:

gcc -c foo.cgcc -c bar.car rc mylibrary.a foo.o bar.o

For more information about this, read the GCC manual manual to learn how to use the compiler, and the linker via the compiler. Thebinutils manual should alsobe helpful.

Answer 2: The GNU Make manual is prettygood. To really learn about libraries and how they work, read the Linkers and Loadersbook by John R. Levine.

Static libraries are pretty simple, but shared libraries can be very hairy, dependingon the platform and the amount of portability you want and need. As an example, onsome systems static and shared libraries must be compiled with different optionsto work properly (one must and the other must not be compiled with position independentcode). Whole frameworks of utilities have been developed to make this easier (libtool),but they are not unproblematic themselves.