一、概念性区别
const 变量就是在普通变量前边加上一个关键字const,它赋值的唯一机会就是“定义时”,此变量不能被程序修改,存储在rodata区。
define定义的是常量,不是变量,所以编译器就不会给define定义的宏名字分配存储单元。通常来说,编译器对常量的处理方式是嵌入到代码中,以立即数的方式出现。
二、测试
1、const测试
const测试程序
#include <stdio.h>
#include <stdlib.h>
const char ch = 'a';
int Main()
{
volatile int i = 5;
printf("hello,embeded world %d\n",i);
#include <stdlib.h>
const char ch = 'a';
int Main()
{
volatile int i = 5;
printf("hello,embeded world %d\n",i);
}
反汇编
Disassembly of section .rodata: 00000000 <ch>: 0: 00000061 andeq r0, r0, r1, rrx
2、define测试
define测试程序
#include <stdio.h>
#include <stdlib.h>
#define ch 'a'
int Main()
{
volatile int i = 5;
printf("hello,embeded word %c\n",ch);
#include <stdlib.h>
#define ch 'a'
int Main()
{
volatile int i = 5;
printf("hello,embeded word %c\n",ch);
}
反汇编
00000000 <Main>:
0: e1a0c00d mov ip, sp
4: e92dd800 stmdb sp!, {fp, ip, lr, pc}
8: e24cb004 sub fp, ip, #4 ; 0x4
c: e24dd004 sub sp, sp, #4 ; 0x4
10: e3a03005 mov r3, #5 ; 0x5
14: e50b3010 str r3, [fp, #-16]
18: e59f000c ldr r0, [pc, #12] ; 2c <.text+0x2c>
1c: e3a01061 mov r1, #97 ; 0x61
20: ebfffffe bl 20 <Main+0x20>
24: e1a00003 mov r0, r3
28: e89da808 ldmia sp, {r3, fp, sp, pc}
2c: 00000000 andeq r0, r0, r0
0: e1a0c00d mov ip, sp
4: e92dd800 stmdb sp!, {fp, ip, lr, pc}
8: e24cb004 sub fp, ip, #4 ; 0x4
c: e24dd004 sub sp, sp, #4 ; 0x4
10: e3a03005 mov r3, #5 ; 0x5
14: e50b3010 str r3, [fp, #-16]
18: e59f000c ldr r0, [pc, #12] ; 2c <.text+0x2c>
1c: e3a01061 mov r1, #97 ; 0x61
20: ebfffffe bl 20 <Main+0x20>
24: e1a00003 mov r0, r3
28: e89da808 ldmia sp, {r3, fp, sp, pc}
2c: 00000000 andeq r0, r0, r0