How to Create Shared Objects under Mac OS X

Some time ago a friend from Colombia asked me how to create a Shared Object under Mac OS X in order to be able to use it from a Python application (via ctypes).

Although the compiler most commonly used on Mac OS X is the GCC compiler, the version supplied by Apple has a handful of modifications which are specific for OS X. In particular, the -shared compiler flag, used to create Shared Objects under GNU/Linux based systems, has no effect.

In spite of this, Apple did introduce its own mechanism for creating Shared Objects along its GCC extensions. Assuming we have a file called mylibrary.c, which contains the source code for our library, we should invoke GCC like so:

If the compiling process succeeds, this command should create a file called mylibrary.dylib, which can now be dynamically linked from other applications.

Unlike Linux based Operating Systems, Mac OS X seems to automatically add the current working directory to the DYLD_LIBRARY_PATH environment variable (an equivalent to Linux’s own LD_LIBRARY_PATH), thus it should not be required to modify this variable in order to have our applications link against the newly created library at runtime, unless, of course, we wanted to move the Shared Object to a directory different from where our process will be executing.

Finally, it should be taken into account that this mechanism is just a simplified example. A correct way to manage the library creation process would be by means of make or equivalent software construction applications, which provide several advantages to software developers.