如果您的数组是在文件级别定义的(您提到了lut.h),并且两者都有const 限定符,它们将不会加载到 RAM 中¹。 static 关键字仅限制数组的范围,它不会以任何方式改变其生命周期。如果您检查代码的程序集,您将在编译时看到两个数组 look exactly the same:
static const int static_array[] = { 1, 2, 3 };
const int extern_array[] = { 1, 2, 3};
extern void do_something(const int * a);
int main(void)
{
do_something(static_array);
do_something(extern_array);
return 0;
}
生成的程序集:
main:
sub rsp, 8
mov edi, OFFSET FLAT:static_array
call do_something
mov edi, OFFSET FLAT:extern_array
call do_something
xor eax, eax
add rsp, 8
ret
extern_array:
.long 1
.long 2
.long 3
static_array:
.long 1
.long 2
.long 3
另一方面,如果你在函数内部声明数组,那么数组will be copied to temporary storage(堆栈)在函数执行期间,除非你添加static限定符:
extern void do_something(const int * a);
int main(void)
{
static const int static_local_array[] = { 1, 2, 3 };
const int local_array[] = { 1, 2, 3 };
do_something(static_local_array);
do_something(local_array);
return 0;
}
生成的程序集:
main:
sub rsp, 24
mov edi, OFFSET FLAT:static_local_array
movabs rax, 8589934593
mov QWORD PTR [rsp+4], rax
mov DWORD PTR [rsp+12], 3
call do_something
lea rdi, [rsp+4]
call do_something
xor eax, eax
add rsp, 24
ret
static_local_array:
.long 1
.long 2
.long 3
¹ 更准确地说,它取决于编译器。一些编译器将需要额外的自定义属性来准确定义您想要存储数据的位置。当有足够的空闲空间时,一些编译器会尝试将数组放入 RAM 中,以加快读取速度。