|
#include <stdio.h>
int f( short x ); // Declare f !!
int main( int argc, char *argv[])
{
short a = 2;
int b;
b = f( a ); // *** Use f( )
printf("a = %d, b = %d\n", a, b);
}
int f( short x )
{
return(x*x);
}
|
| File 1 (p1.c) | File 2 (p2.c) |
|---|---|
#include <stdio.h>
int f( short x ); // Declare f !!
int main( int argc, char *argv[])
{
short a = 2;
int b;
b = f( a ); // **** Use f( )
printf("a = %d, b = %d\n", a, b);
}
|
#include <stdio.h>
int f( short x )
{
return(x*x);
}
|
Important note:
|
We can compile this C-program using the following commands:
gcc -c p1.c // Produces: p1.o
gcc -c p2.c // Produces: p2.o
gcc p1.o p2.o // Produces: a.out
|
How to run the program:
|
|
| File 1 (p1.c) | File 2 (p2.c) |
|---|---|
#include <stdio.h>
int f( short x ); // Declare f !!
int main( int argc, char *argv[])
{
short a = 2;
int b;
b = f( a ); // **** Use f( )
printf("a = %d, b = %d\n", a, b);
}
|
#include <stdio.h>
int f( short x )
{
return(x*x*x); // Change in p2.c
}
|
We can re-compile the multi-file C program using the following commands:
1. Re-compile the updated C program source files:
gcc -c p2.c // Produces a new p2.o
2. Link again:
gcc p1.o p2.o // Produce a new a.out
|
Use /home/cs255001/demo/C/Multi-file-prog/p1.c + p2.c to do the demo
To illustrate the linkage step, consider this multi-files C program where the function f( ) in p2.c is changed to g( ):
| File 1 (p1.c) | File 2 (p2.c) |
|---|---|
#include <stdio.h>
int f( short x ); // Declare f !!
int main( int argc, char *argv[])
{
short a = 2;
int b;
b = f( a ); // **** Use f( )
printf("a = %d, b = %d\n", a, b);
}
|
#include <stdio.h>
int g( short x ) // Change in p2.c
{
return(x*x);
}
|
cs255-1@aruba (5244)> gcc -c p1.c // No syntax errors in p1.c cs255-1@aruba (5245)> gcc -c p2.c // No syntax errors in p2.c cs255-1@aruba (5246)> gcc p1.o p2.o // Linkage error !! p1.o: In function `main': p1.c:(.text+0x1c): undefined reference to `f' collect2: error: ld returned 1 exit status |
Reason:
|
Use /home/cs255001/demo/C/Multi-file-prog/p1.c + p2.c to do the demo