Multi-file Programming in C and Code Reuse - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Multi-file Programming in C and Code Reuse

Share This


Sometimes we write some codes that we have already written for previous programs. Here is a small tip that might save you some time. You may make a generic file with reusable functions.

Many languages make this easy to do. Object-oriented languages like Java or C++ for example allow you to take a class with utility functions and then import them into your main program. This way you can use the generic class in all your programs.

Even in C, you can do this by including the generic C file when compiling with a command like:

gcc -o myprogram myprogram.c generic.c
Your generic utility functions would be in generic.c and gcc simply adds the file to myprogram.

In this context, we will discuss two different techniques to work with multi-file programming. Let's check the following examples.


Example-1

This example shows how to include a file in a different file. Here we are including fact.c in another file main.c. Hence, at the time of pre-processing phase of the compilation process,  the file main.c the line will be replaced by the content of fact.c file. Thus after pre-processing, the newly generated file will act as a single file. Let's try the following code sample.

Keep the following files in your present working directory.

Content of main.c

#include <stdio.h> #include "fact.c" int main() { int n; printf("Enter an integer: "); scanf("%d", &n); printf("%d", fact(n)); return 0; }

Content of fact.c

int fact(int n) { int i, res = 1; for (i = 2; i <= n; i++) res *= i; return res; }
Compile the code using $gcc -o test main.c and run the executable file using $./test command.

To understand the compilation process in detail, read Understanding Different Phases of C Program Compilation


Example-2

This example shows, how to compile a code without including required source files in the main program. Keep the following files in your present working directory.

Content of main.c

#include <stdio.h> extern int fact(int n); int main() { int n; printf("Enter an integer: "); scanf("%d", &n); printf("%d", fact(n)); return 0; }

Content of fact.c

int fact(int n) { int i, res = 1; for (i = 2; i <= n; i++) res *= i; return res; }
Compile the code using $gcc -o test main.c fact.c and run the executable file using $./test command.

It is just needless to state that if you know this kind of multi-file programming, then it becomes very easy to reuse code blocks as generic functions.

Happy Exploring!

No comments:

Post a Comment