QUESTION 17
What belongs in a shared header for a simple function?
2 marksAnswer
A compatible prototype and an include guard. Put the ordinary function definition in one source file and compile/link the needed source files together.
QUESTION 17
A compatible prototype and an include guard. Put the ordinary function definition in one source file and compile/link the needed source files together.
QUESTION 18
Multifile programming separates interfaces from implementations so a larger program can be organised and built in parts.
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.
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.
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.
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.
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.
#ifndef CODEBHAVYA_OPERATIONS_H
#define CODEBHAVYA_OPERATIONS_H
int add(int a, int b);
#endif#include "operations.h"
int add(int a, int b) { return a + b; }#include <stdio.h>
#include "operations.h"
int main(void) { printf("Sum = %d\n", add(4, 6)); return 0; }gcc -std=c11 -Wall -Wextra -pedantic main.c operations.c -o program
./programIn Windows PowerShell, use program.exe as the output name and .\program.exe to run it.
The example uses values in the code.
Sum = 10