8

这是一个现场面试问题,我很困惑。

我被要求为 linux 编写一个 Hello world 程序。这也是在不使用系统中的任何库的情况下。我想我必须使用系统调用或其他东西。代码应该使用 -nostdlib 和 -nostartfiles 选项运行。

如果有人能帮忙就好了。。

4

6 回答 6

17
$ cat > hwa.S
write = 0x04
exit  = 0xfc
.text
_start:
        movl    $1, %ebx
        lea     str, %ecx
        movl    $len, %edx
        movl    $write, %eax
        int     $0x80
        xorl    %ebx, %ebx
        movl    $exit, %eax
        int     $0x80
.data
str:    .ascii "Hello, world!\n"
len = . -str
.globl  _start
$ as -o hwa.o hwa.S
$ ld hwa.o
$ ./a.out
Hello, world!
于 2009-11-06T22:40:59.013 回答
9

看一下示例 4(不会因可移植性而获奖):

#include <syscall.h>

void syscall1(int num, int arg1)
{
  asm("int\t$0x80\n\t":
      /* output */    :
      /* input  */    "a"(num), "b"(arg1)
      /* clobbered */ );
}

void syscall3(int num, int arg1, int arg2, int arg3)
{
  asm("int\t$0x80\n\t" :
      /* output */     :
      /* input  */    "a"(num), "b"(arg1), "c"(arg2), "d"(arg3) 
      /* clobbered */ );
}

char str[] = "Hello, world!\n";

int _start()
{
  syscall3(SYS_write, 0, (int) str, sizeof(str)-1);
  syscall1(SYS_exit,  0);
}

编辑:正如下面Zan Lynx所指出的, sys_write的第一个参数是文件描述符。因此,这段代码执行了写入 stdin (fd 0) 而不是 stdout (fd 1) 的"Hello, world!\n"常见事情

于 2009-11-06T22:30:09.580 回答
2

如以下链接中的示例所示,以纯汇编形式编写它怎么样?

http://blog.var.cc/blog/archive/2004/11/10/hello_world_in_x86_assembly__programming_workshop.html

于 2009-11-06T22:38:41.580 回答
1
    .global _start

    .text

_start:
    mov     $1, %rax               
    mov     $1, %rdi                
    mov     $yourText, %rsi          
    mov     $13, %rdx              
    syscall                         

    mov     $60, %rax               
    xor     %rdi, %rdi              
    syscall                         

yourText:
    .ascii  "Hello, World\n"

您可以使用以下命令组装和运行它gcc

$ vim hello.s
$ gcc -c hello.s && ld hello.o -o hello.out && ./hello.out

或使用as

$as hello.s -o hello.o && ld hello.o -o hello.out && ./hello.out
于 2018-07-08T20:32:46.507 回答
0

您必须直接与操作系统交谈。您可以write通过执行以下操作来文件描述符 1 (stdout):

#include <unistd.h>

int main()
{
    write(1, "Hello World\n", 12);
}
于 2009-11-06T22:34:11.990 回答
0

shell脚本呢?我在问题中没有看到任何编程语言要求。

echo "Hello World!"
于 2009-11-06T22:34:13.457 回答