Search code examples
gccinline-assemblycmp

compare values with inline assembler


I'm searching for a code example, for comparing values with inline assembly in gcc. I need to asign values to the asm code. I've tried some examples, they didn't worked correctly. There is always an error or i don't understand the results.

I need just to compare two values and return a result.

  movl my_val, %eax
  cmpl %eax,$0xfffffffa
  je   equal
  equal:
  movl $0xfffffffa,my_val

Solution

  • This program will compare value taken from argv[1] with $0x1 on my amd64, so you might have to fix it to work on your architecture:

    #include <stdio.h>
    
    int main(int argc, char* argv[]) {
    
      int value, result;
      value = atoi(argv[1]);
      result = 0;
    
      __asm__ ( "xor $0x1,%%eax;\n"
        "jnz end;\n"
        "movl $0xfffffffa,%%ebx;\n"
        "end:\n"
        :"=b"(result)
        :"a"(value)
      );
    
      if (result) {
        printf("Equals!\n");
      }
    
      return 0;
    }
    

    Now compile and run it:

    $ gcc -o comp comp.c
    $ ./comp 0
    $ ./comp 1
    Equals!
    

    Reference: