0

我在 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 库?

4

2 回答 2

1

我认为您应该通过将 -lc 选项添加到 ld 参数来将您的程序与 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 代码

# 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 编译器和标准库如何工作的更多信息。

于 2012-07-01T07:52:24.117 回答
0

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

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

-dynamic-linker /lib64/ld-linux-x86-64.so.2 /lib64/libc.so.6
于 2011-07-07T10:38:32.743 回答