I want to practice with assembler inserts. I wanted to write code to calculate the sum of the numbers from 1 to n, implementing it in assembly language. However, he has not yet been able to compile even simple code that writes the value n to sum. Here is the code:
#include <stdio.h> int sumN(int n) { // calculate 1+2+...+n int sum; __asm__( "mov %1, %eax\n\t" "mov %eax, %0\n\t" :"=d"(sum) :"c"(n) :"%eax"); return sum; } int main() { for (int i = 1; i < 100; ++i) { printf("n: %d sum(n): %d\n",i,sumN(i) ); } return 0; } However, the g ++ compiler produces an error.
main.cpp: 11: 11: error: invalid 'asm': operand number missing after% -letter: "% eax");
^
main.cpp: 11: 11: error: invalid 'asm': operand number missing after% -letter.
I thought that the problem is that I did not specify all the registers that I use, so I rewrote the code a bit:
#include <stdio.h> int sumN(int n) { // calculate 1+2+...+n int sum; __asm__( "mov %1, %eax\n\t" "mov %eax, %0\n\t" :"=d"(sum) :"c"(n) :"%eax","%edx","%ecx"); return sum; } int main() { for (int i = 1; i < 100; ++i) { printf("n: %d sum(n): %d\n",i,sumN(i) ); } return 0; } However, such code is not compiled, gcc gives an error
main.cpp: 11:25: error: 'asm' operand has impossible constraints
: "% eax", "% edx", "% ecx");
Tell me, what is the error and how to fix it? PS was guided by this article