
CAVR-4
130
Writing efficient code
AVR® IAR C/C++ Compiler
Reference Guide
Anonymous structures and unions are implemented in terms of objects named after the
first field, with a prefix _A to place the name in the implementation part of the
namespace. In this example, the anonymous union will be implemented through an
object named _A_IOPORT.
Writing efficient code
This section contains general programming hints on how to implement functions to
make your applications robust, but at the same time facilitate compiler optimizations.
The following is a list of programming techniques that will, when followed, enable the
compiler to better optimize the application.
● Local variables—auto variables and parameters—are preferred over static or global
variables. The reason is that the optimizer must assume, for example, that called
functions may modify non-local variables. When the life spans for local variables
end, the previously occupied memory can then be reused. Globally declared
variables will occupy data memory during the whole program execution.
● Avoid taking the address of local variables using the & operator. There are two main
reasons why this is inefficient. First, the variable must be placed in memory, and
thus cannot be placed in a processor register. This results in larger and slower code.
Second, the optimizer can no longer assume that the local variable is unaffected
over function calls.
● Module-local variables—variables that are declared static—are preferred over
global variables. Also avoid taking the address of frequently accessed static
variables.
● The compiler is capable of inlining functions. This means that instead of calling a
function, the compiler inserts the content of the function at the location where the
function was called. The result is a faster, but often larger, application. Also,
inlining may enable further optimizations. The compiler often inlines small
functions declared static. The use of the
#pragma inline directive and the C++
keyword
inline gives you fine-grained control, and it is the preferred method
compared to the traditional way of using preprocessor macros. This feature can be
disabled using the
--no_inline command line option; see --no_inline, page 190.
● Avoid using inline assembler. Instead, try writing the code in C or C++, use intrinsic
functions, or write a separate module in assembler language. For more details, see
Mixing C and assembler, page 93.