Linking Error
Posted in Code
First dog watch, 3 bells (5:31 pm)

I just solved an annoying linking error in Linux. I have a program I'm writing that has two subdirectories in its source directory, and inside those two directories, two static libraries are built. In the parent directory, all objects are built fine, and everything's shiny until it tries to link the final binary, when I get all these undefined reference to `class::class()`, etc. The constructor, destructor, and other functions seem to have disappeared when I link the library to the main application!

Using nm I can see that the library has those symbols defined! What's going on?

Turns out it was a problem with my Makefile where I set up the linking. I was adding the link path and libraries before the object files of the parent directory. I didn't think there was a problem with this as long as everything was on the same command line. Well it looks like I was wrong. When I changed my linking from

g++ -o program_name -Lpath1 -Lpath2 -lstaticlib1 -lstaticlib2 object1.o object2.o ...


g++ -o program_name object1.o object2.o ... -Lpath1 -Lpath2 -lstaticlib1 -lstaticlib2

everything worked perfectly! Sheesh, picky linker!

PS Technically I'm using Makefile variables, so it's easier to read. The actual line looks like this:
$(CC) -o program_name $(OBJ) $(LINK)
but I expanded them for clarity.

Leave a Comment »

Leave a Reply