Hello world without using libraries
This was an onsite interview question and I was baffled.
I was asked to write a Hello world program for linux.. That too without using any libraries in the system. I think I have to use system calls or something.. The code should run using -nostdlib and -nostartfiles option..
It would be gr开发者_如何学运维eat if someone could help..
$ 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!
Have a look at example 4 (won't win a prize for portability):
#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);
}
Edit: as pointed out by Zan Lynx below, the first argument to sys_write is the file descriptor. Thus this code does the uncommon thing of writing "Hello, world!\n"
to stdin (fd 0) instead of stdout (fd 1).
How about writing it in pure assembly as in the example presented in the following link?
http://blog.var.cc/blog/archive/2004/11/10/hello_world_in_x86_assembly__programming_workshop.html
.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"
You can assemble and run this using gcc
:
$ vim hello.s
$ gcc -c hello.s && ld hello.o -o hello.out && ./hello.out
or using as
:
$as hello.s -o hello.o && ld hello.o -o hello.out && ./hello.out
You'd have to talk to the OS directly. You could write
to file descriptor 1, (stdout), by doing:
#include <unistd.h>
int main()
{
write(1, "Hello World\n", 12);
}
What about a shell script? I didn't see any programming language requirement in the question.
echo "Hello World!"
精彩评论