0

I am currently playing around with in-line simply and I've gotten a bit stuck. I have managed to call a function with no parameters but when it comes to calling one with two parameters I get stuck.

My code below should call a function (add) that adds to predefined numbers together and it should call a second one (add parameter) with two parameters which should be added together.


  #include <stdio.h>

  int c = 4;
  int d = 5;
  void add() {
      int result = 1 + 2;
      printf("Result: %d\n", result);
  }

  void add_parameter(int a, int b) {
      int result = a + b;
      printf("Result: %d\n", result);
  }


int main()
{
       __asm__ __volatile__ ( "call add" );

    //    __asm__ __volatile__(
    //     "mov     eax, offset c"
    //     "push    eax"
    //     "mov     eax, offset d"
    //     "push    eax"
    //     "call add_parameter"
    //     "pop     ebx"
    //     "pop     ebx"
    //    );

    __asm__ __volatile__ ( "mov eax, offset c" );
    __asm__ __volatile__ ( "push eax" );
    __asm__ __volatile__ ( "mov eax, offset d" );
    __asm__ __volatile__ ( "push eax" );
    __asm__ __volatile__ ( "call add_parameter" );
    __asm__ __volatile__ ( "pop ebx" );
    __asm__ __volatile__ ( "pop ebx" );

    return 0;
}

My problem at the moment is that when I try to compile the program I get an error that says

p_function.c:31: Error: too many memory references for `mov'
p_function.c:33: Error: too many memory references for `mov'

In my program I've tried two approaches one being one single ASM call with the whole ASM code in it and one where I had split each line into its own asm call.

Unfortunately I am not sure which one of these approaches is correct let alone the most effective but I get the same error regardless of which approach I use. How can I fix this problem and call the function add_parameter

Thanks

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
nad34
  • 343
  • 4
  • 13
  • Even if you used AT&T syntax (or used `gcc -masm=intel` to get it to read this as Intel syntax) to fix the error message you're getting now, it wouldn't be safe to use Basic asm (no constraints); you modify register values, and so could the called function. – Peter Cordes May 22 '21 at 10:23
  • You need to write %eax instead of eax. – EL_9 May 22 '21 at 10:23
  • 1
    I added [Calling printf in extended inline ASM](https://stackoverflow.com/q/37502841) to the list of duplicates as an example of the clobber declarations necessary for calling a function to be safe. (i.e. describe the calling convention via the clobber list). That question is for x86-64 so the actual arg-passing is different (in regs instead of the stack). Your entire approach of using Basic Asm statements inside a function is totally flawed (always use Extended asm), separate from the Intel vs. AT&T syntax mixup. – Peter Cordes May 22 '21 at 10:33

0 Answers0