Incrementing a Variable Using Inline Assembly

I am trying to figure out how to embed assembly language in C (using gcc on x86_64 architecture). I wrote this program to increase the value of one variable. But I get junk value as a way out. And ideas why?

#include <stdio.h>

int main(void) {
    int x;
    x = 4;

    asm("incl %0": "=r"(x): "r0"(x));

    printf("%d", x);
    return 0;
}

      

thank

Update . The program gives the expected output on gcc 4.8.3, but not on gcc 4.6.3. I am pasting an assembly of non-working code:

    .file   "abc.c"
.section    .rodata
.LC0:
.string "%d"
.text
.globl  main
.type   main, @function
 main:
.LFB0:
.cfi_startproc
pushq   %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq    %rsp, %rbp
.cfi_def_cfa_register 6
pushq   %rbx
subq    $24, %rsp
movl    $4, -20(%rbp)
movl    -20(%rbp), %eax

incl %edx

movl    %edx, %ebx
.cfi_offset 3, -24
movl    %ebx, -20(%rbp)
movl    $.LC0, %eax
movl    -20(%rbp), %edx
movl    %edx, %esi
movq    %rax, %rdi
movl    $0, %eax
call    printf
movl    $0, %eax
addq    $24, %rsp
popq    %rbx
popq    %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE0:
.size   main, .-main
.ident  "GCC: (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3"
.section    .note.GNU-stack,"",@progbits

      

+3


source to share


1 answer


You don't have to say twice x

; once is enough:

asm("incl %0": "+r"(x));

      

+r

says that the value will be input and output.



Your path with separate inputs and output registers requires inputting input from %1

, adding one and writing output to %0

, but you cannot do that with incl

.

The reason it works on some compilers is because GCC can allocate both tags %0

and %1

to the same case and seems to have done so in these cases, but it doesn't have to. By the way, if you want to prevent GCC from allocating input and output to the same register (for example, if you want to initialize the output before using the input to compute the final output), you need to use a modifier &

.

Documentation for modifiers is here .

+4


source







All Articles