Tuesday, May 08, 2007

static linking in Mac - But when?

This is a linker part of my Makefile for compiling an app in Linux. It statically links a library which again I did.
Shared Library Generation
gcc  -shared -Wl,-soname,libmylib.so   -o libmylib.so.1.0.1 myownfile.o

App Generation
gcc -o testapp -L/usr/local/lib -L. -lmylib appfile1.o appfile2.o appfile3.o


This went fine in Linux. But, in Mac, the app generation started shouting. Yes, I have to compile it as a dylib file. And I did that too.

libtool -o libmylib.A.dylib myownfile.o -L/usr/local/lib -lotherlib

Ok. All are ready. Now, when I tried to compile it as below (similar to Linux), I was encountered with "undefined symbols", the same functions which I was linking from my dylib file. \

gcc -o testapp -L/usr/local/lib -L. -lmylib appfile1.o appfile2.o appfile3.o


aaaaaaarrggghhhhhh.

Googling led me to a startling (er... a rather novice mistake) revelation. With the above flow, the compiler will first encounter that library, see that it has no use, throw it off and then, try to link the object files. Now (and NOWWWW), it tries to solve the dependencies in the object files. Failing to solve, it shouts back at the user "LOSSEERRRRRR".... :-(

So, with the sombre face of a loser, I changed the compile script to follow the reverse pattern, ie, link the object files first and THEN, solve the dependencies, if any.



gcc -o testapp  appfile1.o appfile2.o appfile3.o -L/usr/local/lib -L. -lmylib



Voila. It works.

I did it! I did it! yeah yeah. I did it!