#include <stdio.h>
int f( float x ); // Declare f !!
int main( int argc, char *argv[])
{
short a = 2;
int b;
b = f( a );
printf("a = %d, b = %d\n", a, b);
}
int f( float x )
{
return(x*x);
}
|
#include <stdio.h>
int main(int argc, char *argv[])
{
short x = 2; // *** short !!!
int y = 0;
y = f(x); // Assumes: int f(int x)
printf("x = %d, y = %d\n", x, y);
}
/* ---------------------------------------------------
Function f( ) is defined AFTER main's use of f( )
--------------------------------------------------- */
int f(float x)
{
return(x*x);
}
|
the C compiler will make a incorrect function prototype assumption:
int f ( int x )
|
when the actual function definition is:
int f(float x)
{
return(x*x);
}
|
cs255-1@aruba (4845)> gcc impl-declare3.c
impl-declare3.c: In function 'main':
impl-declare3.c:9:8: warning: implicit declaration of function 'f' [-Wimplicit-function-declaration]
y = f(x); // C compiler will assume: int f(int x)
^
impl-declare3.c: At top level:
impl-declare3.c:24:5: error: conflicting types for 'f'
int f( float x )
^
impl-declare3.c:25:1: note: an argument type that has a default promotion can't match an empty parameter name list declaration
{
^
impl-declare3.c:9:8: note: previous implicit declaration of 'f' was here
y = f(x); // C compiler will assume: int f(int x)
^
|
How to run the program:
|
|
#include <stdio.h>
int main(int argc, char *argv[])
{
short x = 2; // *** short !!!
int y = 0;
y = f(x); // Assumes: int f(int x)
printf("x = %d, y = %d\n", x, y);
}
/* ---------------------------------------------------
Function f( ) is defined AFTER main's use of f( )
--------------------------------------------------- */
int f(float x)
{
return(x*x);
}
|
| File 1 (q1.c) | File 2 (q2.c) |
|---|---|
#include <stdio.h>
int main( int argc, char *argv[])
{
short a = 2;
int b;
b = f( a ); // **** assumes: int f( int x )
printf("a = %d, b = %d\n", a, b);
}
|
#include <stdio.h>
int f( float x )
{
return(x*x);
}
|
Observe that:
|
When we compile these program files:
cd /home/cs255001/demo/C/Multi-file-prog
gcc -c q1.c
q1.c: In function 'main':
q1.c:9:8: warning: implicit declaration of function 'f' [-Wimplicit-function-declaration]
b = f( a ); // **** assumes: int f( int x )
^
gcc -c q2.c
gcc q1.o q2.o
***** A warning is not fatal !!!
***** Program compiles successfully !!!
|
However, the program will not run correctly:
cs255-1@aruba (4978)> a.out a = 2, b = 0 (correct output is: b = 4) |
Because:
|
| File 1 (q1.c) | File 2 (q2.c) |
|---|---|
#include <stdio.h>
int f(float x); // Declare f !!!
int main( int argc, char *argv[])
{
short a = 2;
int b;
b = f( a ); // Works correctly now
printf("a = %d, b = %d\n", a, b);
}
|
#include <stdio.h>
int f( float x )
{
return(x*x);
}
|
I'll do the demo in class
|
|
We will discuss this next