簡體   English   中英

匯編中局部和全局 scope 中的 const 變量

[英]const variables in local and global scope in assembly

我在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

據我所知,對於在 function(文件的全局變量)之外定義的變量,它會在頂部添加一個 label。 但是,如果是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

全局變量是全局的,在某些段中獲得 memory 賦值,局部變量是局部變量,除非聲明為 static(局部全局變量),否則它們位於堆棧或寄存器中。 Const 只是向編譯器表明它可以基於變量是只讀的而不是讀/寫的假設來生成代碼。 如果您嘗試寫入一個只讀聲明的變量,一個更好的編譯器會抱怨。 所以 const int 和 int 之間的區別是只讀與讀/寫。

如果你不取地址,你不需要在數據 memory 的任何地方保留一個const local。 asm 等效項是 NASM d equ 4或 GAS d = 4 ,因此您可以在需要時將其用作立即數。

與碰巧未被修改的非const int 相同:是的,局部變量的 constness 純粹是編譯器強制執行以幫助您捕獲錯誤的編譯時事物。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM