问题
Simple question. The function asm
in C is used to do inline assembly in your code. But what does it return? Is it the conventional eax
, and if not, what does it return?
回答1:
__asm__
itself does not return a value. C standard does not define how __asm__
should handle the return value, so the behavior might be different between compilers. You stated that Visual Studio example is valid, but Visual Studio uses __asm
. __asm__
is used at least by GCC.
Visual Studio
To get the result in a C program, you should place return value to eax
in the assembly code, and return from the function. The caller will receive contents of eax
as the return value.
Visual Studio 2015 documentation:
int power2( int num, int power )
{
__asm
{
mov eax, num ; Get first argument
mov ecx, power ; Get second argument
shl eax, cl ; EAX = EAX * ( 2 to the power of CL )
}
// Return with result in EAX
}
GCC
GCC inline assembly HOWTO does not contain a similar example. This probably means you cannot use implicit return as in Visual Studio. However, the HOWTO shows that you can store the result to C variable inside the assembly block, and return value of that variable after the assembly block has ended.
An example of a string copy function, returning value of dest
:
static inline char * strcpy(char * dest,const char *src)
{
int d0, d1, d2;
__asm__ __volatile__( "1:\tlodsb\n\t"
"stosb\n\t"
"testb %%al,%%al\n\t"
"jne 1b"
: "=&S" (d0), "=&D" (d1), "=&a" (d2)
: "0" (src),"1" (dest)
: "memory");
return dest;
}
回答2:
It's unlikely; per the C99 spec, under J3 Implementation-defined behaviour:
The asm keyword may be used to insert assembly language directly into the translator output (6.8). The most common implementation is via a statement of the form:
asm ( character-string-literal );
So it's unlikely that an implementor is going to come up with an approach that both inserts the assembly language into the translator output and also generates some additional intermediary linking code to wire a particular register as a return result.
It's a keyword, not a function.
E.g. GCC uses "=r"
-type constraint semantics to allow you in your assembly to have write access to a variable. But you ensure the result ends up in the right place.
来源:https://stackoverflow.com/questions/36802683/does-asm-return-the-value-of-eax