ld Command Examples (with examples)
Link a specific object file with no dependencies into an executable
ld path/to/file.o --output path/to/output_executable
Motivation
This use case is helpful when you have an object file that needs to be linked into a standalone executable file. By using the ld
command, you can link the object file without any additional dependencies, resulting in a self-contained executable.
Explanation
path/to/file.o
: Specifies the path to the object file that needs to be linked.--output path/to/output_executable
: Specifies the path and name of the output executable file.
Example Output
If the object file successfully links into an executable, you will see the newly created executable file at the specified output path (path/to/output_executable
).
Link two object files together
ld path/to/file1.o path/to/file2.o --output path/to/output_executable
Motivation
This use case allows you to link multiple object files together into a single executable. It is useful when you have separate files that need to be combined to create a complete program.
Explanation
path/to/file1.o
andpath/to/file2.o
: Specifies the paths to the object files that need to be linked.--output path/to/output_executable
: Specifies the path and name of the output executable file.
Example Output
If the object files link successfully, you will see the resulting executable file at the specified output path (path/to/output_executable
).
Dynamically link an x86_64 program to glibc
ld --output path/to/output_executable --dynamic-linker /lib/ld-linux-x86-64.so.2 /lib/crt1.o /lib/crti.o -lc path/to/file.o /lib/crtn.o
Motivation
This example demonstrates how to dynamically link an x86_64 program to the GNU C Library (glibc). Dynamic linking allows the program to use shared libraries provided by the operating system, reducing executable size and allowing for easy library updates.
Explanation
--output path/to/output_executable
: Specifies the path and name of the output executable file.--dynamic-linker /lib/ld-linux-x86-64.so.2
: Sets the path of the dynamic linker, which is responsible for resolving and loading shared libraries at runtime./lib/crt1.o
,/lib/crti.o
,/lib/crtn.o
: These are object files required for the C runtime startup and shutdown.-lc
: Specifies the library to link against. In this case,-lc
refers to the C library (glibc).path/to/file.o
: Specifies the path to the object file that needs to be linked.
Example Output
If the linking process completes successfully, you will see the resulting executable file at the specified output path (path/to/output_executable
). The executable will be dynamically linked to glibc, enabling it to utilize the functions and resources provided by the library.