Skip to main content
JohnFrancis
Associate II
July 7, 2025
Solved

Edit the auto-generated code in CubeMX

  • July 7, 2025
  • 1 reply
  • 420 views

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.

Best answer by Andrew Neil

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:

AndrewNeil_0-1751902098831.png

https://www.st.com/resource/en/user_manual/um1718-stm32cubemx-for-stm32-configuration-and-initialization-c-code-generation-stmicroelectronics.pdf#page=509

1 reply

Andrew Neil
Super User
July 7, 2025

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 ...

A complex system that works is invariably found to have evolved from a simple system that worked.A complex system designed from scratch never works and cannot be patched up to make it work.
JohnFrancis
Associate II
July 7, 2025

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?

Andrew Neil
Andrew NeilBest answer
Super User
July 7, 2025

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:

AndrewNeil_0-1751902098831.png

https://www.st.com/resource/en/user_manual/um1718-stm32cubemx-for-stm32-configuration-and-initialization-c-code-generation-stmicroelectronics.pdf#page=509

A complex system that works is invariably found to have evolved from a simple system that worked.A complex system designed from scratch never works and cannot be patched up to make it work.