Basic Example of working with the Multiple Files:
file1.c
void func1()
{
printf("from func1\n");
}
file2.c
void func2()
{
printf("from func2\n");
}
similarly write file3.c, file4.c ... fileN.c and func3()
to func4()
... funcN()
As we have spread our entire program across multiple files, symbols in one .c
file cannot be known to other .c
file, as a result when we compile our program
we will see some warning/errors.
Use of extern
keyword
extern
is a storage class
extern
keyword is to declare the symbols which are defined in other source files.
Though we can directly use extern
to declare symbols in other source files, the best practice is to create a header file(probably same name as that of source file with .h
extension) and give the declarations there.
For all of our .c
files we have created (except main.c) we need to create a .h
file and add the function declaration there.
Ex:
file1.h will have extern void func1();
and
file2.h will have extern void func2();
and so on so forth..
Note: functions by default will have extern
storage class, generally ignored if called in same file where defined.
main.c
/* standard header files */
#include <stdio.h>
/* user defined header files */
#include "file1.h"
#include "file2.h"
/** add other header files here **/
int main()
{
int ch;
printf("enter choice (1-5):");
scanf("%d", &ch);
if(ch == 1)
func1();
else if(ch == 2)
func2();
else if(ch == 3)
func3();
else if(ch == 4)
func4();
else if(ch == 5)
func5();
else
printf("invalied choice\n");
return 0;
}
Compiling multiple files
gcc -Wall main.c file1.c file2.c file3.c file4.c file5.c -o test
./test