I want to calculate a sum of elements of an array using GCC inline assembly as an exercise. I need to access the elements. I tried this code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc) {
unsigned n = 4;
unsigned* a = malloc(sizeof(unsigned) * n);
unsigned s;
a[0] = 4;
a[1] = 1;
a[2] = 5;
a[3] = 7;
__asm__ (
".text;"
" mov %[n], %%ecx;"
" mov $0, %%eax;"
" mov $0, %%ebx;"
"l1:;"
" add %[a][%%ebx], %%eax;"
" add $1, %%ebx;"
" loop l1;"
" mov %%eax, %[s];"
: [s] "=r" (s)
: [a] "r" (a), [n] "r" (n)
);
printf("%u\n", s);
free(a);
return 0;
}
It gives the error:
main.c: Assembler messages:
main.c:15: Error: junk `[%ebx]' after register
Obviously the line add %[a][%%ebx], %%eax;
is wrong. How should I modify it?
Also I would be happy to get some recommendations about optimization of this code.