有没有办法强制C++编译器将变量存储在寄存器中?

Is there a way to force a C++ compiler to store a variable in a register?

本文关键字:存储 变量 寄存器 编译器 C++ 有没有      更新时间:2023-10-16

我知道inline关键字使编译器更有可能内联函数,尽管决定取决于编译器,而 GNU 扩展__attribute__((always_inline))强制编译器内联它。
相应地,有没有...

__attribute__((always_register)) register int foo = 678;

。或类似的东西?

GCC 有一种方法通过使用关键字asmregister来指定局部变量的寄存器:

register int *foo asm ("r12");

请注意引用:

此功能唯一支持的用途是指定寄存器 调用扩展asm时的输入和输出操作数。

此功能在某些体系结构的 Linux 内核中使用,以访问存储在某个通用寄存器中的线程本地存储。这就是宏在 ARC 架构上的实现current方式:

register struct task_struct *curr_arc asm("r25");
#define current (curr_arc)

这种用法很有趣,因为它在全局范围内使用register关键字,而在标准 C 中,它只能在本地使用。