问题描述
以下codeS用于计算的罪
和 COS
值,如果角度给出。为了尽可能快地计算这些功能,组装code实现被采用。
The following codes are used for calculate the sin
and cos
value if the angle is given. In order to calculate these functions as fast as possible, assembly code implementations are adopted.
#include <stdio.h>
float sinx( float degree ) {
float result, two_right_angles = 180.0f ;
__asm__ __volatile__ ( "fld %1;"
"fld %2;"
"fldpi;"
"fmul;"
"fdiv;"
"fsin;"
"fstp %0;"
: "=g" (result)
: "g"(two_right_angles), "g" (degree)
) ;
return result ;
}
float cosx( float degree ) {
float result, two_right_angles = 180.0f, radians ;
__asm__ __volatile__ ( "fld %1;"
"fld %2;"
"fldpi;"
"fmul;"
"fdiv;"
"fstp %0;"
: "=g" (radians)
: "g"(two_right_angles), "g" (degree)
) ;
__asm__ __volatile__ ( "fld %1;"
"fcos;"
"fstp %0;" : "=g" (result) : "g" (radians)
) ;
return result ;
}
float square_root( float val ) {
float result ;
__asm__ __volatile__ ( "fld %1;"
"fsqrt;"
"fstp %0;"
: "=g" (result)
: "g" (val)
) ;
return result ;
}
int main() {
float theta ;
printf( "Enter theta in degrees : " ) ;
scanf( "%f", &theta ) ;
printf( "sinx(%f) = %f\n", theta, sinx( theta ) );
printf( "cosx(%f) = %f\n", theta, cosx( theta ) );
printf( "square_root(%f) = %f\n", theta, square_root( theta ) ) ;
return 0 ;
}
以上codeS来自和我试图编译上面的codeS用gcc:
The above codes comes from here, and I am trying to compile the above codes with gcc:
g++ -Wall -fexceptions -g -c /filename.cpp
然而,它失败,和下面的错误消息被给出:
However, it fails, and the following error messages are given:
Error: operand type mismatch for `fstp'|
Error: operand type mismatch for `fstp'|
我想知道,为什么编译会失败,以及如何我可以成功地编译它们。谢谢!
I was wondering why the compilation would fail and how I can compile them successfully. Thanks!
推荐答案
借助说,大约先按g
约束:任何寄存器,内存或整数立即数是允许的,但对于不是一般寄存器的寄存器
。编译器可能拿起其中 FSTP
不接受,但适合约束的寄存器。
The manual says about g
constraint: Any register, memory or immediate integer operand is allowed, except for registers that are not general registers
. The compiler probably picked a register which fstp
doesn't accept but fits the constraints.
顺便说一句,这是相当可怕的内联汇编。
By the way, this is quite horrible inline asm.
另外请注意,只是因为事情是在ASM,它不一定会更快。编译器是相当能够优化的东西和它做了更好的工作了。你可能会感兴趣的 -ffast-数学
开关。从收益罪(度* M_PI / 180);
编译器生成这一小块code的:
Also note just because something is in asm, it will not necessarily be faster. The compiler is quite capable of optimizing things and it does a better job, too. You might be interested in the -ffast-math
switch. From return sin(degree * M_PI / 180);
the compiler produces this small piece of code:
fldl .LC0
fmuls 4(%esp)
fsin
ret
这篇关于我为什么会有数类型不匹配的错误用gcc编译大会codeS是什么时候?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!