0

I have the following code

#include <stdio.h>

volatile int global_counter = 0;

void increment_counter() {
    for (int i = 0; i < 100000; ++i) {
        //global_counter++;
        asm ("incl %0"
            :"+a"(global_counter)
        );
    }
}

int main() {

    increment_counter();
    printf("Final value of global_counter: %d\n", global_counter);

    return 0;
}

However, gcc with -S -O2 options compiles to the following assembly code

_increment_counter:
LFB1:
    movl    $100000, %edx
    .p2align 4,,10
    .p2align 3
L2:
    movl    _global_counter(%rip), %eax
# 8 "x_test.c" 1
    incl %eax
# 0 "" 2
    subl    $1, %edx
    movl    %eax, _global_counter(%rip)
    jne L2
    ret

It means that the assembly code is compiled to:

    movl    _global_counter(%rip), %eax
    incl %eax
    movl    %eax, _global_counter(%rip)

How can I make it compile to

    incl _global_counter(%rip)

directly without the movl instruction?

Is it possible to make the gcc inline assembly to use the incl instruction directly on the memory, without using the register eax?

4

1 Answer 1

2

I am the OP. Sorry for my fault. It should be "+m" instead of "+a" for using the memory instead of register.

I modified the code to:

        asm ("incl %0":"+m"(global_counter));

Problem solved.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.