Skip to main content
JohnFrancis
Associate III
Jul 7, 2025 3:06 PM UTC
Solved

Edit the auto-generated code in CubeMX

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.

This topic has been closed for replies.
Andrew Neil
Andrew NeilBest answer
Super User
Jul 7, 2025 3:21 PM UTC

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.

5 replies

Andrew Neil
Super User
Jul 7, 2025 3:16 PM UTC

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 III
Jul 7, 2025 3:19 PM UTC

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
Jul 7, 2025 3:21 PM UTC

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.