Create a UNIX (including Linux) Shared Library


Create a UNIX shared library based on a piece of existing code. For example, the following code calculates how many people can be fed by a particular size of birthday cake. The feeds_how_many method in the cake_info class is shown in Listing 1 and Listing 2 below:

Listing 1. libcakeinfo.hpp

enum cake_filling {sponge, fruit}

enum cake_shape {square, round, hexagonal, other}

class cake_info



static short feeds_how_many(short, cake_shape, cake_filling)



Listing 2. libcakeinfo.cpp 

#include "libcakeinfo.hpp"

short cake_info::feeds_how_many(short diameter, cake_shape shape, cake_filling filling)


// Fruit cakes are more filling than sponge cakes

double munch_size_factor = (filling == fruit ? 2.5 : 1)

// The amount of "dead space" (air) in the cake - depends on the shape

double dead_space_factor



case square: dead_space_factor = 0


case hexagonal: dead_space_factor = 0.1


case round: dead_space_factor = 0.15


case other: dead_space_factor = 0.2



short num_consumers = (short)(diameter * munch_size_factor *(1 - dead_space_factor))

return num_consumers




Compile the code into position-independent code, and then convert it to a shared library using the ld command.

To build a shared library, the code must first be compiled as position-independent code, or PIC. PIC can be loaded anywhere in the address space of an application by the dynamic linker, which fixes up references to library method calls made by the application. Under Linux, use the following: 

gcc -fPIC -c libcakeinfo.cpp


The resultant object file, libcakeinfo.o, can then be converted into a shared library using the ld command:

ld -shared -soname -o libcakeinfo.o 


The -shared option indicates that ld should produce a shared library. The -soname option specifies the name and major version number of the library (shared libraries are conventionally given the .so suffix). The full file name of the library is specified using the -o option; notice that this also includes a minor version number and optionally a release number. For more information concerning the use of major and minor version numbers, see the item titled "How to Update a UNIX* (including Linux*) Shared Library."

This item is part of a larger body of items that contrast the ways in which versioning and dynamic linking are handled by Windows* and the .NET Common Language Runtime* (CLR), as opposed to by UNIX-based operating systems such as Linux* or Solaris*.


Versioning, Libraries, and Assemblies


For more complete information about compiler optimizations, see our Optimization Notice.