Skip to study material
← Question index

QUESTION 18

Explain multifile programming, headers, declarations and linking.

5 marks

Answer in brief

Multifile programming separates interfaces from implementations so a larger program can be organised and built in parts.

Example layout

  1. operations.h declares int add(int, int) inside an include guard.
  2. operations.c includes that header and defines add.
  3. main.c includes the header, calls add and displays the result.
  4. The build compiles and links both .c files into one executable.

Header role

The prototype tells each source file how to call the function. The include guard prevents repeated processing of that header’s contents within a translation unit. It does not replace linking, create the function implementation or make multiple ordinary external definitions safe.

Compilation and linking

Each source file is translated using the declarations visible in it. The linker then connects references to definitions from object files and libraries. A function declaration with no linked definition can lead to a link failure. Keep prototypes and definitions compatible.

Shared data

Declare an externally shared object with extern in a header and define it in one source file when such sharing is needed. Prefer clear function interfaces over unnecessary shared mutable state. File-scope static declarations can keep helper names internal to one translation unit.

Benefits and example use

Smaller modules are easier to read, test and maintain. The supplied example has three downloadable files and an exact GCC build command. It is intentionally not presented as one pasteable single-file program; all required source files must be included in the build.

Complete C example

Save all three files in one folder. Compile the two source files together; this example requires a terminal or an environment supporting multiple source files.

operations.h

Download operations.h
#ifndef CODEBHAVYA_OPERATIONS_H
#define CODEBHAVYA_OPERATIONS_H
int add(int a, int b);
#endif

operations.c

Download operations.c
#include "operations.h"
int add(int a, int b) { return a + b; }

main.c

Download main.c
#include <stdio.h>
#include "operations.h"
int main(void) { printf("Sum = %d\n", add(4, 6)); return 0; }

Compile and run

gcc -std=c11 -Wall -Wextra -pedantic main.c operations.c -o program
./program

In Windows PowerShell, use program.exe as the output name and .\program.exe to run it.

Sample input and output

The example uses values in the code.

Output

Sum = 10