Reputation: 301
There is a constant global variable defined in another module.
I would like to manipulate this variable during run time (as I can't change in the other module and remove the const keyword).
I know that constants are put in ROM ...
The code will be downloaded to a micro controller (leopard powerpc 5643) , so I think that constants will be in the Flash Memory (not the normal PC ROM)
I have tried something like this and the compiler produced an error during compilation:
const int global_Variable = 0;
const int* ptr = &global_Variable;
*ptr = 5;
So , do you know any other way to accomplish this ?
Upvotes: 2
Views: 122
Reputation: 399803
If you know that the constant really is put into ROM (or, more likely, flash) on your platform, then of course you won't be able to modify it, at least not directly.
If it's flash, you might, but you're going to have to dive a bit deeper since reprogramming flash memory is not done by just writing to it, you must erase the relevant portion and there are often block/sector size limitations to deal with. It won't be pretty.
Your actual code fails to compile since you can't write through a const
pointer (that's the point of the const
, after all). You can cast away that and force the compiler to generate the write, but of course it won't work if the target address points to non-writable memory:
const int global_Variable = 0;
int *ptr = (int *) &global_Variable; /* Cast away the const. */
*ptr = 5; /* Do the write! */
Again, this won't work if global_Variable
is in non-writable memory. You will get undefined results.
Lastly, which is so obvious that I didn't even think to write it: what you're doing sounds lika a very bad idea. Obviously the software you're working on was designed with the assumption that global_Variable
be constant. You're trying to overthrow that particular part of the design, which very likely will break lots of things if you succeed. In other words: consider not doing this.
Upvotes: 4
Reputation: 92986
If you manage to place global_variable
in a memory region that is writeable, here is a way to change its value. Notice that this won't work if global_variable
is not physically writeable, e.g. because it sits in the ROM area.
int *ptr = (int*)&global_variable; /* the compiler will warn you about this */
*ptr = 5;
Notice that you might run into other problems down the road as the compiler might assume that the content of a variable declared as const
does not change during the runtime of the program. You violate this assertion by altering the variable's value, so expect strange results.
Upvotes: 0