In my code I have many of constants have same value. I cannot use same name of constant due to logic.
On optimization will keil take different memory of each or same memory.
I am using three setting of optimization: 1. O0 2. Cross + microlib + O2 3. Cross + Time + O3
Just to be clear, are you saying constant folding can be applied to constant variables, in addition to constant literals?
For example:
void func(void) { int a = 5; int b = a * 3; //... }
I would expect the optimizer to do the math and assign b = 15;
Where as:
const int a = 5; void func(void) { int b = a * 3; //... }
I would expect the expression "a * 3" to be evaluated at runtime.
The wikipedia article doesn't mention the second example, with constant variables.
Just note that 'const' means different things in C or C++.
In C++, the language allows it to be used as size of arrays etc. So really full constant folding optimizations all out with better compilers.
Care to explain what made you form that expectation? I ask because I'm pretty sure that expectation is unfounded. Any C compiler worth having will make 'a' as unmodifiable as it possibly can (read-only page configured in the MMU, or even actual ROM), and perform 'a*3' at compile time.
There's absolutely no sane reason for a C compiler to expect 'a', as defined, to ever change past compile time, and therefore no reason for it to delay evaluation of a*3 until runtime. You entered a two-way promise, a.k.a. "contract", with the C compiler by flagging a 'const'. The contract is that neither your code, nor the C compiler, will ever modify 'a'. If you plan on violating that contract in ways the C compiler has no way of knowing about (e.g. modifying the hex file before burning, or re-flashing at runtime) it is your responsibility to tell the compiler about that by amending the contract. You do that like this:
volatile const int a = 5;