Creating dynamic libraries under Mac OS X

So you are compiling some piece of C code, possibly ancient, possibly written for Linux, and you get to the place where a library is about to be created, and you get something like:

stany@gilva:~/src/socks/socks5-v1.0r11/shlib[05:16 AM]$ gcc -o libsocks5_sh.so  
-shared msg.o protocol.o log.o hostname.o confutil.o buffer.o cache.o wrap.o 
wrap_tcp.o wrap_udp.o conf.o libproto.o select.o rld.o null.o addr.o 
upwd.o gss.o   -ldl  
gcc: unrecognized option `-shared'
ld: warning multiple definitions of symbol _gethostbyname2
hostname.o definition of _gethostbyname2 in section (__TEXT,__text)
[....]
ld: Undefined symbols:
_main
stany@gilva:~/src/socks/socks5-v1.0r11/shlib[05:16 AM]$ 

And you get all confuzzled.

Well, unrecognized option `-shared’ warning is not generated by gcc, but by ld, which is the dynamic linker, and is amongst other things in charge of creating dynamic libraries (and static archive files). Of course, dynamic libraries are just collections of functions, and do not need main(). Under Linux, and most other unices (Including Solaris), -shared is what ld wants in order to create a dynamic library. However, Darwin is different, and linker expects -dynamiclib instead.

So:

stany@gilva:~/src/socks/socks5-v1.0r11/shlib[05:16 AM]$ gcc -o libsocks5_sh.so 
-dynamiclib msg.o protocol.o log.o hostname.o confutil.o buffer.o 
cache.o wrap.o wrap_tcp.o wrap_udp.o conf.o libproto.o select.o  rld.o 
null.o addr.o upwd.o gss.o   -ldl  
ld: warning multiple definitions of symbol _gethostbyname2
hostname.o definition of _gethostbyname2 in section (__TEXT,__text)
[...]
stany@gilva:~/src/socks/socks5-v1.0r11/shlib[05:19 AM]$ file libsocks5_sh.so 
libsocks5_sh.so: Mach-O dynamically linked shared library ppc
stany@gilva:~/src/socks/socks5-v1.0r11/shlib[05:20 AM]$ 

However, in spite of it’s magical properties, it doesn’t fix the function name clashes. 🙂