汇编语言与所有其他语言略有不同,因此与您在其他语言中习惯的方式不同。例如,您可以使用 C++ 或许多其他语言来执行此操作:
string s = "hello"
string d = "hello"
if (s == d) {}
在汇编中,您不能执行上述操作,因为您没有如此好的抽象可供您使用。你离机器很近,所以你必须自己做很多繁重的工作。
您的代码无法正常工作有几个原因
mov $[name], %eax # move name into eax
上述指令会将name的地址移动到%eax。所以之后当你这样做时:
cmp %eax, %ebx
它比较两个地址,而不是“值”。
例如,如果我们想将mov 字符串的“值”写入寄存器,我们将编写:
mov name, %eax
这里重要的是%eax 只能包含 32 位(4 字节)的数据。因此,如果您的字符串是“Hello”,%eax 将仅包含 4 个字节“olle”。由于字节顺序而倒序。这极大地限制了我们,但我们还有其他方法可以绕过它。
我们可以使用cmpsb,只要我们有一个最小长度可以使用。
#our strings
.data
name: .string "Hello"
constname: .string "Hello"
# other instructions...
mov $(name), %edi # move the "Address" of name into edi
mov $(constname), %esi # move "Address" of constname into esi
mov $5, %ecx # compare 5 characters only, you can use string1 length here
rep cmpsb # rep `cmpsb` (Compare String Byte), till %ecx is 0
jz if # Success, jump to if label if zero flag is set
call else # Strings were not equal
# other stuff...
if: # if label
旁注:
我强烈建议您使用$(..) 语法而不是$[...]。 AT&T 语法已经充满了复杂的语法,所以让我们坚持使用最常用的一种。例如$name、$(name) 和$[name] 都是同一个意思。