Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions

  




 

 

2.8 Using library header files

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):

#include <stdio.h>  

int
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.


 
 
  Published under the terms of the GNU General Public License Design by Interspire