UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

4.3.  Function prototypes

The compiler works only with the information contained in the file it is processing, for this reason it is often needed to inform the compiler that a function is defined in another file. This is done inserting instead of the function definition (already present in other file) its prototype. A function prototype is a line similar to the first line of its declaration: result type followed by the function name and the comma separated types of the parameters surrounded by parenthesis. Every function invoked must be preceded by either its definition or its prototype. The function prototype and its definition can be present in the same file. The following example illustrates this situation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* Prototype */
int addition(int, int);
/* Main function */
int main() 
{
    int i, j;

    i = 10;
    j = 20;
    /* Function invocation */
    i += addition(i, j);
}
/* Function definition */
int addition(int a, int b) 
{
    return (a + b);
}

Suggestion

Copy and paste the previous example in a text file in your development environment and compile the program with the command gcc -Wall -o program file.c, replacing file.c by the name of your file. If the compiler prints no messages, the program is syntactically correct. Try to remove the prototype in line 2 and compile again. If you move the function definition starting in line 14 to the top of the file, Do you still need the prototype? What happens if you still include it? What happens if the function and the prototype do not agree in the type of the parameters or the result type?