补充:如何搭建一个编写汇编的环境
上次忘记提到了这一点,毕竟虽然汇编不是经常要写,但是学的时候还是亲手写写好。Windows下有专属的MASM,还有Linux和Windows通用的NASM。Windows上的都是开箱即用的,然而Linux的方案通常都不是现成的。在Linux环境下另外一个办法就是用GAS(GNU Assembler)
在一个CS汇编课程里可以找到这样的Hello World例子:
.global _start
.text
_start:
# write(1, message, 13)
mov $1, %rax # system call 1 is write
mov $1, %rdi # file handle 1 is stdout
mov $message, %rsi # address of string to output
mov $13, %rdx # number of bytes
syscall # invoke operating system to do the write
# exit(0)
mov $60, %rax # system call 60 is exit
xor %rdi, %rdi # we want return code 0
syscall # invoke operating system to exit
message:
.ascii "Hello, world\n"
上述代码保存为Hello.s,然后用以下命令汇编并链接
gcc -c hello.s && ld hello.o
就可以得到Linux下一个可执行的ELF文件,在此基础上还可以加个SASM作为IDE
虽然我还没有找到基于这种环境教材,不过这里的课程笔记可以参考一下。当然还有另外一种办法就是上面提到的内联汇编,目前我们常用的C编译器都支持这个特性。也就是说,理论上符合格式的代码可以用内联汇编的办法写在main函数里面,然后用gcc或者Windows下VS的编译器编译,gcc版的大概长这样:
int main(){
__asm__ __volatile__(
//此处一行一指令,指令用双引号引起来,比如
"mov $eax , 1\n\t"
);
return 0;
}