关于3.1 const常量的存放位置,应该存在在.rodata只读数据段,见如下实验: ubuntu 20.04 gcc9.4.0 下面程序: #include <stdio.h> ​ (30951)#define HELLO "world\n" const int i = 10; int const j = 20; char *p = "hello ubuntu\n"; int main(void){        char c_val = 'a';        printf("hello%s",HELLO);        printf("%s",p);        printf("c_val = %c\n",c_val);        return 0; }使用gcc编译之后,使用objdump -j .rodata -s a.out之后得到 a.out:     file format elf64-x86-64 ​ Contents of section .rodata: 2000 01000200 0a000000 14000000 68656c6c ............hell 2010 6f207562 756e7475 0a00776f 726c640a o ubuntu..world. 2020 0068656c 6c6f2573 00257300 635f7661 .hello%s.%s.c_va 2030 6c203d20 25630a00                   l = %c..然后通过readelf -s a.out和readelf -S a.out可以看到变量i和j通过const修饰后也放在了.rodata段。 ​ [18] .rodata           PROGBITS         0000000000002000  00002000       0000000000000038  0000000000000000   A       0     0     4 [25] .data             PROGBITS         0000000000004000  00003000       0000000000000018  0000000000000000 WA       0     0     8 ​    54: 0000000000002008     4 OBJECT GLOBAL DEFAULT   18 j    67: 0000000000002004     4 OBJECT GLOBAL DEFAULT   18 i    56: 0000000000004010     8 OBJECT GLOBAL DEFAULT   25 p ​可以看到字符串常量,const型常量存放在只读数据区,但是指针p是在.data段的
点赞

相关推荐

牛客网
牛客企业服务