next up previous
Next: Pointers Up: September lecture summary Previous: Sample C program


September 13

Our sample C program included a function printf from the standard I/O library. You can declare and define your own functions:

    /* add.c
     * a simple C program
     */
      
    #include <stdio.h>
    #define LAST 10
    
    void Incr(int *num, int i);
      
    int main()
    {
        int i, sum = 0;
       
        for ( i = 1; i <= LAST; i++ ) {
            Incr(&sum, i); /* add i to sum */
        } /*-for-*/
        printf("sum = %d\n", sum);

        return 0;
    }

    void Incr(int *num, int i) {
        *num = *num + i;
    }
Several things are going on here
  1. There is a declaration of Incr.
  2. There is a definition of Incr.
  3. Since I want to change the value of sum, I need to pass its address to Incr. The & can be thought of as the ``address-of'' operator, and the * can be thought of as the ``value-at'' operator.

The include file <stdio.h> provides a declaration, but not a definition, of printf. If this is omitted, C will make assumptions about the return type and parameter list for printf -- and these assumptions may well be wrong!

During the first compilation pass, the C compiler turns add.c into object code (machine language), making a note that it will link to printf and Incr. Linking to Incr is internal: its definition is in the same compilation unit (file) as its declaration and use. Linking to printf is implicit: the compiler links to an enormous library object (the C library) without even asking your permission. Occasionally you'll have to specify that the compiler should link to a non-standard library, such as libm.o, which has math.h as a header. This is the reason for the -l m required at the end of a compilation command that some of you saw during the problem session Wednesday afternoon.



Subsections
next up previous
Next: Pointers Up: September lecture summary Previous: Sample C program
Danny Heap 2002-12-16