Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When i should use ld instead of gcc?

Tags:

gcc

linker

ld

I want to know when i should use ld linker instead off gcc. I just wrote a simply hello world in c++, of course i include iostream library. If i want make a binary file with gcc i just use:

g++ hello hello.cpp and i've got my binary file.

Later i try to use ld linker. To get object file i use: g++ -c hello.cpp. Ok that was easy, but the link command was horrible long:

ld -o hello.out  hello.o \
   -L /usr/lib/gcc/x86_64-linux-gnu/4.8.4/ \
   /usr/lib/gcc/x86_64-linux-gnu/4.8.4/crtbegin.o \
   /usr/lib/gcc/x86_64-linux-gnu/4.8.4/crtend.o \
   /usr/lib/x86_64-linux-gnu/crti.o \
   /usr/lib/x86_64-linux-gnu/crtn.o \
   /usr/lib/x86_64-linux-gnu/crt1.o \
   -dynamic-linker /lib64/ld-linux-x86-64.so.2 -lstdc++ -lc 

I know fact that gcc uses the ld. Using gcc is better in all cases or just in most cases? Please, tell me somethink about cases where ld linker has advantage.

like image 247
Ice Avatar asked Apr 17 '16 18:04

Ice


People also ask

What is ld used for?

Description. The ld command, also called the linkage editor or binder, combines object files, archives, and import files into one output object file, resolving external references. It produces an executable object file that can be run.

What is ld in C++?

Updated: 11/06/2021 by Computer Hope. On Unix-like operating systems, ld is a linker. It combines many compiled object and archive files, relocates their data, and ties up symbol references.

What is ld in Ubuntu?

ld combines a number of object and archive files, relocates their data and ties up symbol references. Usually the last step in compiling a program is to run ld.

Is gcc a linker?

GCC uses a separate linker program (called ld.exe ) to perform the linking.


1 Answers

As you mentioned, gcc merely acts as a front-end to ld at link time; it passes all the linker directives (options, default/system libraries, etc..), and makes sure everything fits together nicely by taking care of all these toolchain-specific details for you.

I believe it's best to consider the GNU toolchain as a whole, tightly integrated environment (as anyone with an experience of building toolchains for some exotic embedded platforms with, say, dietlibc integration will probably agree).

Unless you have some very specific platform integration requirements, or have reasons not to use gcc, I can hardly think of any advantage of invoking ld directly for linking. Any extra linker-specific option you may require could easily be specified with the -Wl, prefix on the gcc command line (if not already available as a plain gcc option).

like image 137
xbug Avatar answered Nov 03 '22 05:11

xbug