One Mach-O feature that hits many people by surprise is the distinction between shared libraries and dynamically loadable modules. On ELF systems both are the same; any piece of shared code can be used as a library and for dynamic loading. Use otool -hv some_file to see the filetype of some_file.
Mach-O shared libraries have the file type MH_DYLIB and carry the extension .dylib. They can be linked against with the usual static linker flags, e.g. -lfoo for libfoo.dylib.
Loadable modules are called "bundles" in Mach-O speak. They have the file type MH_BUNDLE. Since no component involved cares about it, they can carry any extension. The extension .bundle is recommended by Apple, but most ported software uses .so for the sake of compatibility.
In this tutorial we are going to build a shared library:
The source code
helloworld.c
1 #include <stdio.h>
2 void printHelloWorld(void)
3 {
4 printf("Hello World!\n");
5 }
6
helloworld.h
1 void printHelloWorld(void);
main.c
1 #include "helloworld.h"
2 int main(int argc, char **argv)
3 {
4 printHelloWorld();
5 }
6
Compiling the library
$ gcc -dynamiclib -o libhello.dylib -dy helloworld.c
$ ls -al
total 64
drwxr-xr-x 7 xappsoftware xappsoftware 238 15 Dic 16:48 .
drwx------+ 39 xappsoftware xappsoftware 1326 14 Dic 19:06 ..
-rw-r--r--@ 1 xappsoftware xappsoftware 6148 14 Dic 19:06 .DS_Store
-rw-r--r-- 1 xappsoftware xappsoftware 78 12 Dic 11:21 helloworld.c
-rw-r--r-- 1 xappsoftware xappsoftware 28 12 Dic 11:21 helloworld.h
-rwxr-xr-x 1 xappsoftware xappsoftware 8456 15 Dic 16:48 libhello.dylib
-rw-r--r-- 1 xappsoftware xappsoftware 81 12 Dic 11:24 main.c
Verifing the Library
$ file libhello.dylib
libhello.dylib: Mach-O 64-bit dynamically linked shared library x86_64
$
Compiling an application
$ gcc -L. -lhello -o mainsl main.c
$ ls -al
total 88
drwxr-xr-x 8 xappsoftware xappsoftware 272 15 Dic 16:51 .
drwx------+ 39 xappsoftware xappsoftware 1326 14 Dic 19:06 ..
-rw-r--r--@ 1 xappsoftware xappsoftware 6148 14 Dic 19:06 .DS_Store
-rw-r--r-- 1 xappsoftware xappsoftware 78 12 Dic 11:21 helloworld.c
-rw-r--r-- 1 xappsoftware xappsoftware 28 12 Dic 11:21 helloworld.h
-rwxr-xr-x 1 xappsoftware xappsoftware 8456 15 Dic 16:48 libhello.dylib
-rw-r--r-- 1 xappsoftware xappsoftware 81 12 Dic 11:24 main.c
-rwxr-xr-x 1 xappsoftware xappsoftware 8784 15 Dic 16:51 mainsl
Testing the application
$ ./mainsl
Hello World!
$