This article discusses the tradeoff between the ease of debugging and the
effectiveness of compiler optimization, while building with TI C/C++
compilers. It does not apply when building with other compilers.
# The Tradeoff Described
Ease of debugging is characterized by things such as:
* Does single stepping proceed through the code exactly as written? Or, does
it skip around in seemingly random order?
* Are all variables always available for inspection? Or do some go missing?
* Do the values in the variables correspond to what is expected at that point
in execution? Or something else?
Effectiveness of compiler optimization is characterized by things such as:
* How fast does the code run?
* Is the code size small enough?
* Is power consumption low enough?
The compiler's main job is to generate instructions and data directives which
implement the C/C++ source code. In addition, the compiler also emits
information used by the debugger to keep track of things like where variables
are located, or how to map an instruction address to a C source line.
The essential problem is that things the compiler does to make the code run
faster may, at the same time, make the code harder to debug. Consider this
for (i = 0; i < COUNT; i++)
sum += array[i];
This loop is counting up, from 0 to COUNT. Suppose, to make it run faster, the
compiler generates code which counts down, from COUNT to 0. What is the
meaning of the variable i? If you inspect the value of i during execution of
the loop, would it be confusing?
This is a simple example, contrived to illustrate the tradeoff. Actual
instances in practice are usually more complex, sometimes much more complex.
# What to Do
Control this tradeoff with the compiler switch --opt_level=*value*. The
*value* can `off`, or `0`-`4`. Though some compilers do not support
`--opt_level=4`. Consult your compiler manual for the details. Here is how
the value affects the tradeoff.
Which level is best varies for each system. For most users, the best
tradeoff point is the lowest level of optimization which meets your system
contraints. Your system constraints are usually some combination of size,
speed, and power. Increase your optimization level until you meet your
constraints. A higher level of optimization, while perhaps worthwile, incurs
a risk to your debug experience.
What if the optimization level you need to meet your constraints is too hard
to debug? Consider lowering the optimization level for just the one file you
need to debug, and not the whole system. In CCS, use the
[File Specific Options](http://software-dl.ti.com/ccs/esd/documents/users_guide/ccs_project-management.html#file-specific-options)
feature. By lowering the optimization level for just one file, it is likely
you will continue to meet your system constraints, while making it easier to
debug that file.