M
M
Mykola Kulik2020-01-13 23:11:37
GCC
Mykola Kulik, 2020-01-13 23:11:37

What's wrong with nested assembler code?

I work on a virtual machine, in ubuntu. Started working in gcc. I took an assembler and tried to make an adder. But something went wrong.
The code:

#include <iostream>
#include <stdio.h>
using namespace std;

int main(int argc, char** argv)
{
  int a, b, c;
  cin >> a;
  cin >> b;
  
  asm (
    "mov a, %eax \n\t"
    "mov b, %ebx \n\t"
    "add %eax, %ebx \n\t"
    "mov %ebx, c \n\t"
  );

  printf("%d", c);
  return 0;
}

I'm compiling , and here the garbage happens:
[email protected] : ~/Documents $ g++ -C -o test test.cpp
/usr/bin/ld: /tmp/cccT2YRx.o: relocation R_X86_64_32S against non-insignificance symbol `a' can not be used when making a PIE object; hijack recollect with -fPIC
/usr/bin/ld: residual linkage probe failed: Split, unsuitable for data collection
collect2: error: ld returned 1 exit status
Can anyone explain what's wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2020-01-13
@PythonistGit

asm (
    "mov a, %eax \n\t"
    "mov b, %ebx \n\t"
    "add %eax, %ebx \n\t"
    "mov %ebx, c \n\t"
  );

So it doesn't work in gcc. It should be like this for example:
asm (
    "mov %[a], %%eax \n\t"
    "mov %[b], %%ebx \n\t"
    "add %%eax, %%ebx \n\t"
    "mov %ebx, %[c] \n\t"
    : [c] "=rm" (c)
    : [a] "rm" (a), [b] "rm" (b)
    : "eax", "ebx", "cc"
  );

What it all means can be read here .
The error says that the code tried to access the global symbol a, but there is no such symbol. Because the variable ais located on the stack and it really does not have a symbolic name. If it (together with band c) were global, there would still be an error (at least when compiling for 64 bits), but different.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question