2025-07-07 8:06 AM - last edited on 2025-07-07 8:13 AM by Andrew Neil
Is there a way to edit the auto-generated code in CubeMX, such as in the function below?
please see the code below:
void MX_USART2_UART_Init(void)
{
/* USER CODE BEGIN USART2_Init 0 */
/* USER CODE END USART2_Init 0 */
/* USER CODE BEGIN USART2_Init 1 */
/* USER CODE END USART2_Init 1 */
huart2.Instance = USART2;
#ifdef SLOW_CLOCK
huart2.Init.BaudRate = 9600;
#else
huart2.Init.BaudRate = 152285;
#endif huart2.Init.WordLength = UART_WORDLENGTH_8B;
...
}
Edited to apply source code formatting - please see How to insert source code for future reference.
2025-07-07 8:16 AM
Of course you can edit it.
But any edits outside the USER CODE BEGIN ... USER CODE END marker comments will be lost if you re-generate the code.
You can set set CubeMX to make backups when you re-generate and/or you can keep your own backups - to help you re-apply any edits ...
2025-07-07 8:19 AM
But is there a way to make edits outside the /* USER CODE BEGIN ... */ and /* USER CODE END ... */ markers without losing them when the code is re-generated?
2025-07-07 8:21 AM - edited 2025-07-07 8:29 AM
No.
The only edits that are retained over re-generating are those within User Code sections. That is the whole point of the User Code sections.
PS:
2025-07-07 8:29 AM
No you can't. Except if you de-init the peripheral and reconfigure it again in /* Code USER xxx */ block.
2025-07-09 4:08 AM
The user code section method described here is less useful for serious SW development IMHO. Quite often I have to make small changes in generated code, HAL and even 3rd party sources. But I try to keep generated code almost as is and do most stuff in additional files.
I use 2 directories, one directory "cube" used for auto-generated code and a second "work" directory which is compiled. Both dirs are maintained in seperate GIT repos. Code changes in generated code are manually merged via Diff tool. Sounds like overkill but has several advantages and makes a programmers life safe and easier.