cancel
Showing results for 
Search instead for 
Did you mean: 

cubemx with keil generate code optimize level problem report

lqi
Associate II

my project is making TF card a Udisk ,I use cubemx generate keil project, when I use AC6 -O0, everything goes fine,I connect USB, the Udisk display , read ,write is OK, but when I set -O1 or -O2, the Udisk won't come out and shows unknown USB device,when I set -O3 is fine,I try to set  optimize level group by group , only "Middlewares/USB_Device_Library" -O1 or -O2 cause this problem, I dont know if it is ST USB library problem

1 REPLY 1
Ghofrane GSOURI
ST Employee

Hello @lqi 

the issue you are facing is directly related to compiler optimization.

When you use -O1 or -O2, the compiler changes how it generates code to make it faster and smaller. This can cause problems in your code or in the USB middleware, such as:

1- Missing volatile qualifiers on variables shared between interrupts and main code, causing the compiler to optimize away or cache values incorrectly.
2- Uninitialized variables that may work at -O0 but not at higher optimization.
3- Timing or order of operations changing due to optimization, which can break timing-sensitive protocols like USB.

Just because -O3 works does not mean the code is correct or robust. The underlying issue is still present, and it may reappear with future code changes, compiler updates, or on different hardware.

This type of problem is a common side effect when enabling compiler optimizations in embedded projects, especially when using complex middleware such as USB stacks. To resolve the issue, carefully review your code (and the middleware) to ensure proper use of volatile, correct variable initialization, and robust timing.

THX

Ghofrane

To give better visibility on the answered topics, please click on Accept as Solution on the reply which solved your issue or answered your question.