我试图理解"static"
修饰符在C中是如何工作的,我go 寻找它的含义,我发现的一切似乎都有点模糊.
它是一个修饰符,允许变量的值一直存在到程序执行结束.
我理解它的含义和用途,但除了这个定义之外,我还想了解它下面是如何工作的,所以我生成了C代码的汇编
char *thing(char *a)
{
char *b;
b = malloc(3);
b[0] = 'y';
b[1] = '\0';
return (b);
}
char *some(int fd)
{
static char *a = "happened";
a = thing(a);
return (a);
}
我用非静态a
变量创建了另一个代码
/* With static variable */
.file "static_test.c"
.text
.globl thing
.type thing, @function
thing:
.LFB6:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
subq $32, %rsp
movq %rdi, -24(%rbp)
movl $3, %edi
call malloc@PLT
movq %rax, -8(%rbp)
movq -8(%rbp), %rax
movb $121, (%rax)
movq -8(%rbp), %rax
addq $1, %rax
movb $0, (%rax)
movq -8(%rbp), %rax
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE6:
.size thing, .-thing
.globl some
.type some, @function
some:
.LFB7:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
subq $16, %rsp
movl %edi, -4(%rbp)
movq a.0(%rip), %rax
movq %rax, %rdi
call thing
movq %rax, a.0(%rip)
movq a.0(%rip), %rax
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE7:
.size some, .-some
.section .rodata
.LC0:
.string "happened"
.section .data.rel.local,"aw"
.align 8
.type a.0, @object
.size a.0, 8
a.0:
.quad .LC0
.ident "GCC: (GNU) 12.1.0"
.section .note.GNU-stack,"",@progbits
/* no static variable */
.file "nostatic_test.c"
.text
.globl thing
.type thing, @function
thing:
.LFB6:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
subq $32, %rsp
movq %rdi, -24(%rbp)
movl $3, %edi
call malloc@PLT
movq %rax, -8(%rbp)
movq -8(%rbp), %rax
movb $121, (%rax)
movq -8(%rbp), %rax
addq $1, %rax
movb $0, (%rax)
movq -8(%rbp), %rax
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE6:
.size thing, .-thing
.section .rodata
.LC0:
.string "happened"
.text
.globl some
.type some, @function
some:
.LFB7:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
subq $32, %rsp
movl %edi, -20(%rbp)
leaq .LC0(%rip), %rax
movq %rax, -8(%rbp)
movq -8(%rbp), %rax
movq %rax, %rdi
call thing
movq %rax, -8(%rbp)
movq -8(%rbp), %rax
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE7:
.size some, .-some
.ident "GCC: (GNU) 12.1.0"
.section .note.GNU-stack,"",@progbits
问题是,这两个汇编代码之间发生了什么以及它们之间的区别,以及它们在编译时和程序执行时的行为.