A Code Monkey's Blog

Understand gcc -L option and library search order

In my project of porting wxGTK from GTK+2 to GTK+3, I built GTK+3 from scratch and installed it at a non-standard location. One of the painful things was that the gcc linker complained about the unknown references to glib or functions. The reason was that I had two parallel glib-2.0.so, one was the system default at /usr/lib64, the other was from my custom build. In the makefile, the gcc linker was given three -L options, something like

-L/usr/lib64 blah blah blah -L/home/foo/gtk3/libs blah blah blah -L/usr/lib64

Apparently, one of two options -L/usr/lib64 took higher priority in the library search order so that my custom glib-2.0.so was not found. But which one was the culprit? I did a little experiment and it turned out that the first masked my custom GTK+3 lib path. So the conclusion is if you have several -L

options the library search order will be 'first-come-first-search'.

The next question is how to solve it. In the makefile, linker flags were specified by something like this:

$(CXX) blah blah blah $(LDFLAGS) $(EXTRALIBS_FOR_GUI) $(LIBS)

In my case, the default setting for $(LDFLAGS) is '-L/usr/lib64', $(EXTRALIBS_FOR_GUI)='-L/home/foo/gtk3/libs' and $(LIBS)='-L/usr/lib64'. Since the makefile was generated by configure which is effected by the environmental variables such as LDFLAGS, doing the following solved my problem:

export LDFLAGS='-L/home/foo/gtk3/libs'

re-run configure

Your mileage may vary. But hope this post can give some hints for your own problems especially if you use parallel libraries.