你好世界没有使用库

use*_*296 8 linux libraries

这是一个现场采访问题,我感到很困惑.

我被要求为linux编写一个Hello world程序..这也没有在系统中使用任何库.我想我必须使用系统调用或什么..代码应该使用-nostdlib和-nostartfiles选项运行..

如果有人可以提供帮助,那就太好了..

Dig*_*oss 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!
Run Code Online (Sandbox Code Playgroud)

  • 我不知道这是否会起作用,但如果确实如此,它会获得+1令人敬畏,如果没有,它会获得+1的chutzpah. (2认同)

Ste*_*202 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);
}
Run Code Online (Sandbox Code Playgroud)

编辑:正如下面Zan Lynx所指出的,sys_write的第一个参数是文件描述符.因此,这个代码写的稀罕事了"Hello, world!\n"标准输入(FD 0),而不是标准输出(FD 1).