Compiling a Program65
This is because the compiler can easily determine that all of the variables are static and
there is no need to assign values and then calculate the sum at the run time. All of this can be
done at the compile time. You can also verify this fact in a debugger. The optimized code will
skip over assignment lines (lines 6 to 8) and will directly jump to the
printf
statement when
you step through.
However in the following code, the compiler can’t make such decisions because the num-
bers
a
and
b
are entered interactively.
1 #include
2 main ()
3 {
4 int a, b, sum;
5
6 printf("Enter first number: ");
7 scanf("%d", &a);
8 printf("Enter second number: ");
9 scanf("%d", &b);
10
11 sum = a+b;
12
13 printf("The sum is: %d\n", sum);
14 }
If you compile this code with different levels of optimization (e.g., –O1 and –O2), and
then trace it through a debugger, you will see a difference in execution sequence because of the
way the compiler makes decisions at the compile time.
It may be mentioned that optimization is not always beneficial. For example, code optimi-
zation changes timings or clock cycles when the code is executed. This especially may create
some problems on embedded systems if you have debugged your code by compiling without
optimization. The rule of thumb is that you should create optimized code instead of relying on
the compiler to make optimization for you.
For a detailed list of optimization options, please see all options starting with –
f
command
line option. However options starting with –
O
are the most commonly used in the optimization
process.
3.3.6Static and Dynamic Linking
A compiler can generate static or dynamic code depending upon how you proceed with the
linking process. If you create static object code, the output files are larger but they can be used as
stand-alone binaries. This means that you can copy an executable file to another system and it
does not depend on shared libraries when it is executed. On the other hand, if you chose dynamic
linking, the final executable code is much smaller but it depends heavily upon shared libraries. If
you copy the final executable program to another system, you have to make sure that the shared
libraries are also present on the system where your application is executed. Please note that ver-
sion inconsistencies in dynamic libraries can also cause problems.
Next Page >>
<< Previous Page
Back to the Table of Contents