Example: the following C program that consists of 2 program files:
main1.c | func1.c |
---|---|
#include <stdio.h>
// Notice: no function declaration used
int main(int argc, char *argv[])
{
int a = 4, b;
b = square(a);
printf("square(%d) = %d\n", a, b);
}
|
int square( int x )
{
int r;
r = x * x;
return ( r );
}
|
Commands used to compile this C program:
gcc -c main1.c # Compile main1.c
gcc -c func1.c # Compile func1.c
gcc -o main1 main1.o func1.o # Link
|
DEMO: demo/C/set4/main1.c + func1.c
The resulting program ran correctly because the implicit function prototype assumption was correct
main1.c | func1.c |
---|---|
#include <stdio.h> // Notice: no function declaration used int main(int argc, char *argv[]) { int a = 4, b; // Assumed: b = square(a); // int square(int) printf("square(%d) = %d\n", a, b); } |
int square( int x )
{
int r;
r = x * x;
return ( r );
}
|
Run time errors will occur when the implicit function prototype assumption was incorrect
We will see an example next
Suppose the data type of the input parameter x of square( ) was float
main2.c | func2.c |
---|---|
#include <stdio.h> // Notice: no function declaration used int main(int argc, char *argv[]) { int a = 4, b; // Assumed: b = square(a); // int square(int) printf("square(%d) = %d\n", a, b); } |
int square( float x )
{
int r;
r = x * x;
return ( r );
}
|
The implicit function prototype assumption used by the C compiler is now incorrect
|
DEMO: demo/C/set4/main2.c + func2.c
The C compiler compiles each C program file separately:
Recall: data type information in one C program is not used in the compilation of other C programs
When the C compiler find the square(x) function call it assumes: square( int )
(This is the C compiler's implicit function declaration mechanism)
The implicit function declaration was wrong:
which results in the run time error (because a wrong code was used to represent the values)
Question: how can we fix this missing data type problem:
main2.c | func2.c |
---|---|
#include <stdio.h> // Notice: no function declaration used int main(int argc, char *argv[]) { int a = 4, b; b = square(a); // Use function printf("square(%d) = %d\n", a, b); } |
int square( float x )
{
int r;
r = x * x;
return ( r );
}
|
DEMO: demo/C/set4/main2.c + func2.c
Provide the C compiler with the data type information by using a (function) declaration:
main2.c | func2.c |
---|---|
#include <stdio.h> int square( float x ) ; // Declaration int main(int argc, char *argv[]) { int a = 4, b; b = square(a); // Use function printf("square(%d) = %d\n", a, b); } |
int square( float x )
{
int r;
r = x * x;
return ( r );
}
|
DEMO: demo/C/set4/main2.c + func2.c
|