Search code examples
gccld

What's the relationship between "gcc linking" and "ld linking"?


It's said that linux loader is /usr/bin/ld, but usually we use gcc/g++ to link libraries and executables, we barely use "ld".

The last time I used "ld" manually was when I was learning linux assembly, the only way to generate executable is to ld a .o file to generate executable directly without any library.

My question is, is gcc/g++ containing some function wrappers of "ld", because raw "ld" is too difficult to use? Or we should never use "ld" explicitly for c/c++ program linking, because of blablabla?


Solution

  • gcc supplies a few default options to ld.

    ld doesn't know anything about C++, or any other language. ld has no idea what libraries your code needs to link with. If you try to link your compiled C++ code with ld directly, it'll bail out on you, since ld, by itself, has no idea where it can find libstdc++, gcc's C++ runtime library. Do you use strings? vectors? Most of that is template code that gets compiled as part of your object module. But there are a still few precompiled bits, in libstdc++, that need to be linked with.

    When you give your compiled code to gcc to link, gcc will be courteous enough to pass all your files along to ld, and tell ld which libraries, in addition to any ones you explicitly specify.

    You can link with ld directly, if you want to, as long as you specify the same libraries and link option gcc uses. But why would you want to do that? Just use gcc to link your gcc-compiled code.