简体   繁体   中英

Assembler code in C

I'm trying to put a assembler code into my C function. This function purpose is to copy value stored in src address to dst address:

void copy(int *dst, int *src);

My actual problematic code:

void copy(int *dst, int *src)
{
    asm("mov %1, %2"
        : /* no output */
        : "i" (dst),
          "i" (src)
        : ""
    );  
}

Giving me errors:

test.c: In function 'copy':
test.c:29: error: unknown register name '' in 'asm'
test.c:29: warning: asm operand 0 probably doesn't match constraints
test.c:29: warning: asm operand 1 probably doesn't match constraints

Line 29 is this line:
asm("mov %1, %2"

EDIT:

asm("mov %0, %1"
    : "=m" (dst)
    : "m" (dst),
      "m" (src)
    : ""
    );

Now gives me:
error: unknown register name '' in 'asm' I do not know what to do with the last section.

EDIT2

I've read that I cant mov memory->memory, I need to use registers. And also I need to use AT&T syntax so it goes like "mov src,dest". Code below compiles, but unfortunately value in address pointed by dst is 0, instead of value I put in address pointed by src.

asm("movl %1, %%eax \n\t"
    "movl %%eax, %0 \n\t"
    : "=m" (dst)
    : "m" (dst),
      "m" (src)
    );

EDIT3

I did it this way (changed parameters) and it works now:

void copy(int *dst, int *src, int n)
{
    int a = *src;
    int b = *dst;
    asm("movl   %1, %%eax\n"
        "movl   %%eax, %0\n"
        : "=m" (b)
        : "m" (a)
        );
    *src = a;
    *dst = b;    
}

You have an empty entry in your clobber section. You don't need that.

Try this:

asm("mov %0, %1"
    : "=m" (dst)
    : "m" (dst),
      "m" (src)
    /* no clobbers */
    );

That code is precisely equivalent to this:

*dst = *src

so I presume this is just small example?

The code compiles, but gives:

t.c: Assembler messages:
t.c:2: Error: too many memory references for `mov'

So I think your assembler instruction needs work, but the compiler syntax is OK.

You can use:

void copy(int *dst, int *src)
{
  __asm__ __volatile__(
    "movl (%0), %%eax\n" 
    "movl %%eax, (%1)\n"
    :
    : "r"(src), "r"(dst)
    : "%eax"
  );
}

which is equivalent to:

mov    (%edx), %eax   ; eax = *src
mov    %eax, (%ecx)   ; *dst = eax

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM