汇编中局部和全局范围内的 const 变量

标签 c assembly gcc x86

我在 Compiler Exporer 中编译了以下 C 代码查看它如何处理 const 关键字:

int a=1;
const b=2;
int func () {
    int c=3;
    const int d=4;
}

        .section        .data
a:
        .long   1
        .section        .rodata
b:
        .long   2
func:
        pushq   %rbp
        movq    %rsp, %rbp
        movl    $3, -4(%rbp)
        movl    $4, -8(%rbp)
        nop     # also, why does it add a nop here?
        popq    %rbp
        ret

据我所知,对于在函数外部定义的变量(文件全局),它会在顶部添加一个标签。但是,如果它是 const 变量,则顶部的变量将放置在只读部分中。我的问题是针对以下局部变量:

const int d=4;

它的“常量”是如何管理的,因为它只是堆栈上的一个值,并且堆栈上的任何值都不能自由修改?或者,在汇编中,是否不存在常量局部变量之类的东西,而这只是编译器强制执行的概念?

最佳答案

试试吧。

int fun ( void )
{
    const int d=4;
    return(d);
}

00000000 <fun>:
   0:   e3a00004    mov r0, #4
   4:   e12fff1e    bx  lr



int fun ( void )
{
    const int d=4;
    return(d);
}
int fun1( void )
{
    int d=4;
    d=5;
    return(d);
}
int fun2 ( void )
{
    const int d=4;
    d=5;
    return(d);
}

so.c: In function ‘fun2’:
so.c:16:6: error: assignment of read-only variable ‘d’


int fun ( void )
{
    const int d=4;
    return(d);
}
int fun1( void )
{
    int d=4;
    d=5;
    return(d);
}

00000000 <fun>:
   0:   e3a00004    mov r0, #4
   4:   e12fff1e    bx  lr

00000008 <fun1>:
   8:   e3a00005    mov r0, #5
   c:   e12fff1e    bx  lr

全局变量是全局变量,在某个段中获取内存分配,局部变量是局部变量,除非声明为静态(局部全局变量),否则它们位于堆栈或寄存器中。 Const 只是向编译器表明它可以基于变量只读而不是读/写的假设来生成代码。如果您尝试写入只读声明的变量,更好的编译器会提示。所以 const int 和 int 之间的区别是只读和读/写。

关于汇编中局部和全局范围内的 const 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63643768/

相关文章:

c - 我收到此错误 "solution.c:9:4: warning: implicit declaration of function ' stricmp' [-Wimplicit-function-declaration] x= stricmp(ap,c);"

assembly - 将 i386 操作码解码为指令

c++ - CMAKE_COMPILER_IS_GNUCXX 和 CMAKE_CXX_COMPILER_ID 为空

c - 如何从 C 源代码和 asm 输出逆向工程结构细节?

c++ - 在默认模板参数中调用 constexpr

objective-c - 在 C 中访问 Apple Earbud Clicker 控件

c++ - 实时 2D 渲染到系统内存

在C中创建一个二进制文件

c++ - 使用 C 中系统调用的文件描述符

assembly - 如何确定何时设置零标志、符号标志、溢出标志和进位标志?