2024-07-02 12:23 AM
Hi, community,
I am converting a TI CCS project into STM32 project.
In the TI CCS project, a const array is defined in the file array.c, e.g.
const uint16_t ARRAY[] = {0, 1, 2, 3, 4, 5};
and in the main.c, the array is recast as
extern uint16_t ARRAY[];
and the user can update the array elements without any error, e.g.
ARRAY[1] = 3;
When I put the files into STM32CubeIDE, the compiler didn't complain about the recast and assignment, but
ARRAY[1] = 3;
didn't execute correctly. When I trace the variable value in debug mode, the ARRAY[1] = 1.
Thanks for reading my post and I look forward to your suggestions and solutions to my question.
Solved! Go to Solution.
2024-07-02 12:35 AM - edited 2024-07-02 12:39 AM
const is a keyword that tells the compiler you are not going to change it and thus you are not allowed to do so, because it will result in undefined behavior. The compiler is free to store it in RAM or ROM. So sometimes it can work if it happens to be stored in RAM.
The compiler can complain depending on the settings. In this case you tell the linker, not the compiler, about the array not being const. The linker might not complain. I always declare extern variables in a header file and include the header file in the source file. That way the compiler will complain if there is a mismatch.
The proper way to do what you want is to copy the array to a non-const array instead of incorrectly linking it. Or to modify the original to be non-const.
2024-07-02 12:35 AM - edited 2024-07-02 12:39 AM
const is a keyword that tells the compiler you are not going to change it and thus you are not allowed to do so, because it will result in undefined behavior. The compiler is free to store it in RAM or ROM. So sometimes it can work if it happens to be stored in RAM.
The compiler can complain depending on the settings. In this case you tell the linker, not the compiler, about the array not being const. The linker might not complain. I always declare extern variables in a header file and include the header file in the source file. That way the compiler will complain if there is a mismatch.
The proper way to do what you want is to copy the array to a non-const array instead of incorrectly linking it. Or to modify the original to be non-const.
2024-07-02 12:41 AM
Thank you unsigned_char_array,
Yes, by changing the array to non-const solves the problem but potentially does not retain the initial value. I tested the way to copy the const array to a non-const array, and it works.