When using a library it is essential to include the appropriate header files, in order to declare the function arguments and return values with the correct types. Without declarations, the arguments of a function can be passed with the wrong type, causing corrupted results.
The following example shows another program which makes a function call to the C math library. In this case, the function pow
is used to compute the cube of two (2 raised to the power of 3):
#includeint main (void) { double x = pow (2.0, 3.0); printf ("Two cubed is %f\n", x); return 0; }
However, the program contains an error--the #include
statement for ‘math.h’ is missing, so the prototype double pow (double x, double y)
given there will not be seen by the compiler.
Compiling the program without any warning options will produce an executable file which gives incorrect results:
$ gcc badpow.c -lm $ ./a.out Two cubed is 2.851120 (incorrect result, should be 8)
The results are corrupted because the arguments and return value of the call to pow
are passed with incorrect types.(6) This can be detected by turning on the warning option -Wall
:
$ gcc -Wall badpow.c -lm badpow.c: In function `main': badpow.c:6: warning: implicit declaration of function `pow'
This example shows again the importance of using the warning option -Wall
to detect serious problems that could otherwise easily be overlooked.
No comments:
Post a Comment