gpt4 book ai didi

c - gcc内联汇编错误

转载 作者:太空宇宙 更新时间:2023-11-04 01:29:00 25 4
gpt4 key购买 nike

我正在努力学习如何编写 gcc 内联汇编。

下面的代码应该执行 shl 指令并返回结果。

#include <stdio.h>
#include <inttypes.h>

uint64_t rotate(uint64_t x, int b)
{
int left = x;
__asm__ ("shl %1, %0"
:"=r"(left)
:"i"(b), "0"(left));

return left;
}

int main()
{
uint64_t a = 1000000000;
uint64_t res = rotate(a, 10);
printf("%llu\n", res);
return 0;
}

编译失败,出现错误:asm 中不可能的约束

问题基本上出在 "i"(b) 上。我已经尝试了 "o""n""m" 等,但它仍然不起作用。要么是这个错误,要么是操作数大小不匹配

我做错了什么?

最佳答案

正如所写,你的代码对我来说编译正确(我启用了优化)。不过,我相信您可能会发现这样更好一些:

#include <stdio.h>
#include <inttypes.h>

uint64_t rotate(uint64_t x, int b)
{
__asm__ ("shl %b[shift], %[value]"
: [value] "+r"(x)
: [shift] "Jc"(b)
: "cc");

return x;
}

int main(int argc, char *argv[])
{
uint64_t a = 1000000000;
uint64_t res = rotate(a, 10);
printf("%llu\n", res);
return 0;
}

请注意,“J”代表 64 位。如果您使用的是 32 位,“I”是正确的值。

其他注意事项:

  • 您要将旋转值从 uint64_t 截断为 int?你在编译 32 位代码吗?我不相信 shl 在编译为 32 位时可以进行 64 位旋转。
  • 在输入约束上允许“c”意味着您可以使用可变的旋转量(即在编译时不进行硬编码)。
  • 因为 shl 修改了标志,所以使用“cc”让编译器知道。
  • 使用 [name] 形式使 asm 更易于阅读 (IMO)。
  • %b 是修饰符。参见 https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#i386Operandmodifiers

如果您想真正了解内联汇编,请查看最新的 gcc 文档:https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html

关于c - gcc内联汇编错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26329487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com