【问题标题】:Hello world without using libraries不使用库的 Hello World
【发布时间】:2009-11-06 22:24:43
【问题描述】:

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

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

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

【问题讨论】:

  • 什么工作,写操作系统内核?

标签: linux libraries


【解决方案1】:
$ 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!

【讨论】:

  • 你能给出代码的“傻瓜汇编”解释吗?
  • 我不知道这是否行得通,但如果行得通,它会因为令人敬畏而获得 +1,如果没有,它会因为胆小而获得 +1。
【解决方案2】:

看看example 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 的第一个参数是file descriptor。因此,这段代码执行了将"Hello, world!\n" 写入stdin (fd 0) 而不是stdout (fd 1) 的罕见事情。

【讨论】:

  • 我认为您希望在您的写入系统调用中使用文件描述符 1。
  • 嘿,你是对的。我看到在该链接页面上的几乎所有示例中,他都写入标准输入而不是标准输出。
【解决方案3】:

如以下链接中的示例那样,用纯汇编编写它怎么样?

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

【讨论】:

    【解决方案4】:
        .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
    

    【讨论】:

      【解决方案5】:

      您必须直接与操作系统对话。你可以 write 到文件描述符 1,(stdout),通过这样做:

      #include <unistd.h>
      
      int main()
      {
          write(1, "Hello World\n", 12);
      }
      

      【讨论】:

      • 你认为“写”从何而来?
      【解决方案6】:

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

      echo "Hello World!"
      

      【讨论】:

      • 即使echo(1) 根本不使用 C 标准库,我很确定这里有一个隐含的“C”语言(或者至少是一个编译的语言)。
      • OP 指定了 gcc 编译器标志,这几乎表明他们在这里考虑了 C
      猜你喜欢
      • 2011-09-12
      • 2014-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-14
      • 1970-01-01
      • 1970-01-01
      • 2016-04-05
      相关资源
      最近更新 更多