简体   繁体   English

汇编:printf不打印新行

[英]Assembly: printf not printing new line

I have the following code that prints the number of parameters passed to ./main . 我有以下代码可以打印传递给./main的参数数量。 Notice the fmt in the rodata section. 请注意rodata部分中的fmt I've included the new line \\n , just like in C , but instead of printing the new line, it prints: 我已经在C中加入了新行\\n ,但是它不是打印新行而是打印:

Number of parameters: 1 \\n 参数数量:1 \\ n

My code is: 我的代码是:

;main.asm
GLOBAL main
EXTERN printf

section .rodata:
fmt db "Number of parameters: %d \n", 0 

section .text:

main:

    push ebp
    mov ebp, esp    ;stackframe

    push dword[ebp+8]       ;prepara los parametros para printf
    push fmt
    call printf
    add esp, 2*4

    mov eax, 0      ;return value

    leave           ;desarmado del stack frame
    ret

I know that including a 10 before the 0 and after the "Number..." in fmt will print it, but I want printf to do it. 我知道在fmt的“ Number ...”之前的0之前和之后包括10都会打印它,但是我希望printf做到这一点。 I assemble the code with NASM and then link it via GCC to create my executable. 我用NASM汇编代码,然后通过GCC将其链接以创建我的可执行文件。

When you use quotes or double quotes around a string in NASM , it doesn't accept C style escape sequences. 当您在NASM中对字符串使用双引号或双引号时,它不接受C样式转义序列。 On Linux you can encode \\n as ASCII 10 like this: 在Linux上,您可以将\\n编码为ASCII 10,如下所示:

fmt db "Number of parameters: %d", 10, 0 

There is an alternative. 还有一种选择。 NASM supports backquotes (backticks) which will allow NASM to process the characters between them as C style escape sequences. NASM支持反引号(反引号),这允许NASM将它们之间的字符作为C样式转义序列进行处理。 This should work as well: 这也应该工作:

fmt db `Number of parameters: %d \n`, 0

Please note: Those are not single quotes, but backticks . 请注意:这些不是单引号,而是反引号 This is described in the NASM documentation : NASM文档中对此进行了描述:

3.4.2 Character Strings 3.4.2字符串

A character string consists of up to eight characters enclosed in either single quotes ('...'), double quotes ("...") or backquotes ( ... ). 一个字符串最多由八个字符组成,这些字符包含在单引号('...'),双引号(“ ...”)或反引号( ... )中。 Single or double quotes are equivalent to NASM (except of course that surrounding the constant with single quotes allows double quotes to appear within it and vice versa); 单引号或双引号与NASM等效(当然,用单引号将常数引起来可以使双引号出现在反之亦然); the contents of those are represented verbatim. 这些内容按原样表示。 Strings enclosed in backquotes support C-style -escapes for special characters . 用反引号引起来的字符串支持C样式的特殊字符转义

The assembler is not C. The C compiler understands \\n as an escape code for ASCII 10. The assembler does not and treats it as two characters. 汇编程序不是C。C编译器将\\ n理解为ASCII 10的转义代码。汇编程序不会将\\ n视为两个字符。 Add the 10 as you describe. 按照您的描述添加10。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM