最“小”的Hello world C程序, From《程序员的自我修养--链接、装载与库》

/*
* The smallest program.
* gcc -c -fno-builtin -m32 TinyHelloWorld.c //在64位系统下,用”-m32”强制用32位ABI去编译, 否则编译不过。ABI--Application Binary Interface,ABI指的是二进制层面的接口,API指的是源代码级别的接口
* ld -static -m elf_i386 -e nomain -o TinyHelloWorld TinyHelloWorld.o //在64位系统增加 -m elf_i386,否则链接错误。64位系统默认链接可执行文件
*用的是elf_x86_64.x, 32位用的是elf32_x86_64.x
*/

char* str = "Hello world!\n";

void print()
{
//使用write系统调用,write的调用号为4,原型为int write(int filedesc, char* buffer, int size)
asm( "movl $13, %%edx \n\t" //str的长度
"movl %0, %%ecx \n\t" //缓冲区,这里的%0指的是"r"后面的字符串地址,也就是传入到这段汇编的参数。
"movl $0, %%ebx \n\t" //stdout, 0
"movl $4, %%eax \n\t" //write的系统调用号
"int $0x80 \n\t" //0x80系统调用中断,eax为调用号(write 为4)。
::"r"(str):"edx", "ecx", "ebx"); //传入的参数列表,ebx/ecx/edx等通用寄存器
//用来传递参数。ebx传递filedesc,stdout为0,所以ebx=0;ecx=str;edx=size=13
}

void exit()
{
asm( "movl $42, %ebx \n\t"
"movl $1, %eax \n\t"
"int $0x80 \n\t");
}

void nomain()
{
print();
exit();
}

 

参考:https://blog.csdn.net/neuq_jtxw007/article/details/78112672

https://stackoverflow.com/questions/11372024/what-does-the-gcc-error-message-error-unsupported-for-mov-mean

https://www.linuxquestions.org/questions/programming-9/assembly-error-i386-architecture-incompatible-with-i386-x86-64-output-827609/

posted @ 2021-11-15 00:01  平安1111  阅读(132)  评论(1)    收藏  举报