CubeMX generates incorrect init order for USB PCD + USBX Device
Hello I found this issue, I drop you my report (with IA helping to write it :) )
**Component/Tool:** STM32CubeMX (code generation)
**MCU:** STM32C071KBT3 (STM32C0 family)
**FW Package:** STM32Cube FW_C0 V1.4.0
**Configuration:** USB Device with USBX CDC-ACM class, bare-metal (no RTOS / no ThreadX)
**Description:**
When generating code for a USB Device project using USBX middleware (CDC-ACM class) in bare-metal mode (without RTOS), STM32CubeMX generates the peripheral initialization calls in `main()` in the wrong order:
Generated code (incorrect):
MX_USB_PCD_Init(); // Called FIRST
MX_USBX_Device_Init(); // Called SECOND**Expected code (correct):**
MX_USBX_Device_Init();
MX_USB_PCD_Init(); **Root cause analysis:**
`MX_USBX_Device_Init()` calls `ux_system_initialize()` and `ux_device_stack_initialize()` which set up the USBX system memory and device stack. The `MX_USB_PCD_Init()` function's USER CODE section then calls `_ux_dcd_stm32_initialize()` which registers the STM32 DCD driver with the USBX device stack.
If `MX_USB_PCD_Init()` is called before `MX_USBX_Device_Init()`, the USBX system and device stack are not yet initialized when `_ux_dcd_stm32_initialize()` attempts to register with them. This results in USB enumeration failure — the device is not recognized by the host.
**Impact:** USB communication completely non-functional with the generated init order. The device does not enumerate on the USB bus.
**Workaround:** Manually reorder the calls in a `USER CODE BEGIN 2` section, calling `MX_USBX_Device_Init()` before `MX_USB_PCD_Init()`. However this workaround is fragile as CubeMX re-generation can overwrite the auto-generated init order section and reintroduce the bug.
**Steps to reproduce:**
1. Create a new STM32CubeMX project for STM32C071KBT3
2. Enable USB in Device mode
3. Add USBX middleware with CDC-ACM class
4. Configure for bare-metal (no RTOS)
5. Generate code
6. Observe that `MX_USB_PCD_Init()` is placed before `MX_USBX_Device_Init()` in the generated `main()` function
**Expected fix:** CubeMX code generator should place `MX_USBX_Device_Init()` before `MX_USB_PCD_Init()` in the generated initialization sequence when USBX middleware is enabled.
Edited to apply proper source code formatting - please see How to insert source code for future reference.
