Sum of two integers by inline asm in C

2

This is my code, I'm running it with gcc on linux, I try to save the result of 3 + 5 in the variable c, and display it on the screen:

  #include<stdio.h>

  int main(){

   double c;

   __asm__  ("movw $0x05,%ax");
   __asm__("movw $0x03,%bx");
   __asm__("add %ax,%bx");
   __asm__("movw %ax,_c");


   printf("%f",c);

   return 0;

  }

The output error is: relocation R_X86_64_32S against undefined symbol '_c' can not be used when making a shared object; recompile with -fPIC

Can someone help me? Thanks

    
asked by Alexmaister 10.01.2018 в 18:58
source

1 answer

4

The first thing I see is that you are using a double to work, but you do not use floating point operations to do the operations, which can cause a misrepresentation of the values (in my opinion).

Depending on what arguments you are compiling the program, you can throw yourself several errors, I have been giving head to your problem and I have found the following solution:

#include <stdio.h>

int main(void) {
    int Valor = 0;

    __asm__("mov $0x05, %%eax\n"
            "mov $0x03, %%ebx\n"
            "add %%eax,  %%ebx\n"
            "mov %%ebx,  %0": "=r" (Valor));
    printf("%d\n", Valor);
    return 0;
}

As far as I understand, it should work with the asm and __asm__ equally, from the%% share% I think it's part of a GCC extension and I do not know if it's available in the compiler you use. Your compiler warns you to compile with : "=r" (Valor)) to generate a standalone executable in memory so that it works even if it is not aligned (as per this answer )

It is worth mentioning that the code I have put up was compiled for 64-bit, although I have changed the names of the registers it should work correctly when changing the names of the registers by the 16 bits, equally when you change the -fPIC by __asm__ .

I hope it has helped you.

    
answered by 11.01.2018 / 20:34
source