使用-dynamic-linker和链接描述文件?

时间:2011-07-07 10:10:53

标签: linux linker ld linker-scripts

我在Intel 32位处理器上使用Linux 2.6.31-14。

C档案:

#include <stdio.h>

main()
{
    printf("Hello World!\n");
}

链接器脚本:

SECTIONS{
    .text 0x00000100 :{
        *(.text)
    }
}

输出:

$ gcc -S test.c 
$ as -o test.o test.s
$ ld -T linker.ld -dynamic-linker /lib/ld-linux.so.2 -o test test.o
test.o: In function `main':
test.c:(.text+0x11): undefined reference to `puts'

有什么问题?如何使链接描述文件使用动态C库?

2 个答案:

答案 0 :(得分:1)

我认为您应该通过向ld参数添加-lc选项将您的程序与C标准库(libc.so)链接。

ld -T linker.ld -lc -dynamic-linker /lib/ld-linux.so.2 -o test test.o

此外,您可能在运行程序时遇到一些问题(分段错误),因为test.o没有程序入口点(_start符号)。因此,您需要额外的目标文件,其入口点在test.o中调用main()函数,而不是通过调用exit()系统调用来执行代码执行。

这是start.s code

# Linux system calls constants
.equ SYSCALL_EXIT, 1
.equ INTERRUPT_LINUX_SYSCALL, 0x80
# Code section
.section .text
.globl _start
_start:                            # Program entry point
    call main                      # Calling main function
# Now calling exit() system call
    movl %eax, %ebx                # Saving return value for exit() argument
    movl $SYSCALL_EXIT, %eax        # System call number
    int $INTERRUPT_LINUX_SYSCALL    # Raising programm interrupt

然后你应该建立你的程序

gcc test.c -S
as test.s -o test.o
as start.s -o start.o
ld start.o test.o -o test -lc --dynamic-linker=/lib/ld-linux.so.2

您可能还想查看这篇文章https://blogs.oracle.com/ksplice/entry/hello_from_a_libc_free,以了解有关C编译器和标准库如何工作的更多信息。

答案 1 :(得分:0)

您没有在c库中进行链接。

在我的64位系统上,它是:

-dynamic-linker /lib64/ld-linux-x86-64.so.2 /lib64/libc.so.6