c++g++ld

g++ links library ld doesn't


I would like to know why

g++ test1.o test2.o -o test.x -lgtk-x11-2.0

works, while

ld 'r test1.o test2.o -o test.o -lgtk-x11-2.0

gives:

ld: cannot find -lgtk-x11-2.0

unless I explicitly include the path adding -L/usr/lib/i386-linux-gnu

I tried everything adding the path to $LD_LIBRARY_PATH or to ld.so.conf but nothing works and I cannot explain myself the difference between the two calls.

On the manual of ld it is specified:

The default set of paths searched (without being specified with `-L') depends on which emulation mode ld is using, and in some cases also on how it was configured

but trying different emulations (by using -m*emulation*) imply segfaulting (probably since the default emulation elf_i386, is the right one).

Can you help me shed light on this topic?


Solution

  • If you are curious about the paths used by ld

    ld --verbose | grep SEARCH
    

    usually you don't want to use ld explicitly for linking, it's probably better to perform every task with gcc alone, and you should prefer the latter over the former.

    If you want to know more about gcc settings

    gcc -dumpspecs
    

    gives you a taste of what it's like to take a look at the internals of gcc, you will probably end up taking a look at the gcc manual if you are serious about this, but I don't think that is something worth doing just for the sake of it.

    Settings defined at the time when gcc was compiled can be important too, so you should also learn how to compile gcc from source if you really want to grasp how the internals work.

    tl;dr

    Just use gcc for both compiling and linking, other options are probably not worth the trouble.