Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linking a dynamically linked executable with ld

Tags:

linux

linker

ld

i'm trying to create a dynamically linked executable (elf_i386) without gcc. The program is very simple (only a printf)...here the commands:

$ gcc -c simple.c
$ ld -o simple -dynamic-linker /lib/ld-linux.so.2 --entry main /usr/lib/crt1.o /usr/lib/crti.o simple.o -lc /usr/lib/crtn.o

The executable is created and also file command and ldd command show the right output... However when i launch the program after the call to printf i get a segmentation fault...i've examined with objdump the executable and i think the problem is about the dtors...seems that compiling with:

$gcc -o simple simple.c

a section .dtors is present while it is not present inside the executable created directly with ld :(

Any ideas?

like image 907
MirkoBanchi Avatar asked Apr 28 '11 15:04

MirkoBanchi


People also ask

Can you statically link a dynamic library?

You can't statically link a shared library (or dynamically link a static one).

How do you make a dynamic link?

Dynamic linking is a two-step process that relies on accessing the addresses of code. The first step occurs at compilation. When a file is compiled with a dynamic library, instead of copying the actual object code contained in the library, the linker simply scans the code contained and checks for missing symbols.

What is dynamic linking with example?

Dynamic linking means that the code for some external routines is located and loaded when the program is first run. When you compile a program that uses shared libraries, the shared libraries are dynamically linked to your program by default.

What are the disadvantages of dynamic linking?

Disadvantages of dynamic linking include the following: From a performance viewpoint, there is "glue code" that is required in the executable program to access the shared segment. There is a performance cost in references to shared library routines of about eight machine cycles per reference.


2 Answers

Lose the --entry main. main isn't your entry point, _start is. Try this:

$ gcc -c hello.c
$ ld -o hello -dynamic-linker /lib/ld-linux.so.2 /usr/lib/crt1.o /usr/lib/crti.o hello.o -lc /usr/lib/crtn.o
$ ./hello
hello, world
$ 
like image 104
Robᵩ Avatar answered Sep 28 '22 06:09

Robᵩ


It is not necessary to include the C run time environment i guess unless you are using return from your main().

We can strip the CRT and just link using :

ld -o hello -lc -dynamic-linker /lib/ld-linux.so.2 hello.o -e main

Will work.

like image 31
mahesh waldiya Avatar answered Sep 28 '22 07:09

mahesh waldiya