Modular Programming
and Standard C library
Modular Programming
• Modular programming is a software design technique that emphasizes breaking
down a program into smaller, independent, and logically organized components
called modules. A module is a self-contained unit of code that performs a specific
task or function.
• Each module is a standalone unit of code that can be written, compiled, and
tested separately from the rest of the program. This allows developers to work on
individual parts without affecting others.
• Each module is designed to perform one specific function or task. For example:
○ A module for input/output operations.
○ A module for mathematical calculations.
○ A module for string manipulation.
cont.
• Modules can be reused in multiple programs. For example, a module that
calculates the square root of a number can be reused in other applications
without rewriting the code.
• Advantage of Modular programming
○ Encourages Code Reuse: Once a module is created, it can be reused in other
programs, reducing redundant code.
○ Simplifies Debugging and Testing: Smaller modules are easier to debug, test,
and verify for correctness.
○ Enhances Readability and Maintainability: Breaking the program into smaller
parts improves the organization of code, making it easier to understand and
modify.
○ Facilitates Teamwork: Different team members can work on separate
modules simultaneously, allowing for clear separation of tasks and faster
development.
cont.
• As mentioned modular programming allow the development of different modules
separately and some of the examples of this are going to be the functions we have
been using like scanf, printf,malloc, calloc, free and others. This functions are a
part of libraries that we have been importing.
• Based on this the developer can also create a module and use it in different
programs by importing as we have been doing on thee above functions.
Building user defined modules
• Modular programming in C allows you to build user-defined modules that can be
reused across multiple programs. These modules are generally separated into two
parts:
○ interface (header file) and
○ implementation (source file).
• However, if you want to create user-defined modules by only importing the source
file, you can do that too. This is known as 'directly including the source file' instead
of using a header file. However, the best practice is to include a header file to
prevent issues such as multiple inclusions, ensure proper declaration of functions
and variables, and promote better code organization and modularity.
Interface (Header File .h)
• The header file defines the function prototypes, constants, macros, and data
structures that are shared among multiple source files. This file acts as a public
interface for other parts of the program.
• A header file contains declarations but no implementations.
• It typically includes:
○ Function prototypes.
○ Macros (#define statements).
○ Constants.
○ Structures and type definitions.
• use include guards to prevent multiple inclusions of the header [Link] include
guards in header files is crucial to prevent multiple inclusions of the same header
file within a single compilation unit.
cont.
• Include guards prevent a header file from being included multiple times by
ensuring that the content of the file is only processed once.
• Here’s how it works:
○ The first time the header file is included, the preprocessor checks if a specific
macro is defined (commonly using #ifndef).
○ If the macro is not defined, the code between #ifndef and #endif is included
in the compilation.
○ The next time the header file is included, the preprocessor sees that the
macro is defined and skips the content of the file.
cont.
#ifndef HEADER_FILE_NAME_H // Check if macro is not defined
#define HEADER_FILE_NAME_H // Define the macro
// Contents of the header file, like function declarations or structure definitions
#endif // End of the #ifndef block
Implementation (Source File .c)
● The source file contains the actual implementation (definitions) of the functions
declared in the header file. It includes the header file so that the function
signatures match.
#include HEADER_FILE_NAME_H // Include header to match the declarations
Data-type Function_one(int a, int b) {
return a + b;
}
Data-type Function_two(int a, int b) {
return a - b;
}
Example
● math_operations.h (header file)
#ifndef MATH_OPERATIONS_H // check if it is defined
#define MATH_OPERATIONS_H // define the macro
int add(int a, int b); // function
int subtract(int a, int b); //function
#endif // end of the if statment
Cont.
● math_operations.c (implementation):
#include "math_operations.h" // Include header to match the declarations
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
Cont.
● main.c (usage):
#include "math_operations.h" // Include header to know function signatures
int main() {
int x = 10, y = 5;
printf("Addition: %d\n", add(x, y)); // Calls the add function
printf("Subtraction: %d\n", subtract(x, y)); // Calls the subtract function
return 0;
}
Linkage
• Linkage in C programming refers to the process by which the linker resolves
references to functions and variables across different translation units (source
files). It determines how names of functions and variables are connected or
treated when they are used in different parts of a program.
• Linkage defines whether different instances of the same name across various
modules refer to the same function or variable, or if they are treated as separate
entities. It plays a key role in ensuring that the right function or variable is
accessed at compile time and runtime.
• There are two types of linkage in C programming
Cont.
• External Linkage:
○ Functions or variables with external linkage are accessible across different
translation units. These can be referenced and used by functions or variables
defined in other source files or modules.
○ This is typically the default linkage for functions and global variables declared
with the extern keyword.
• file1.c
example. #include <stdio.h>
• External Linkage: #include "file1.h" // Include the header file to
provide declarations
• file1.h (header file)
int x = 10; // Variable with external linkage
#ifndef FILE1_H
void print_x() { // Function with external linkage
#define FILE1_H
printf("x = %d\n", x);
}
extern int x; // Declaring external
variable
void print_x(); // Declaring external int main() {
function
print_x(); // Calling function from file1.c
return 0;
#endif
}
cont.
• External Linkage:
• file2.c
#include <stdio.h>
#include "file1.h" // Include the header file to access the functions and
variables from file1.c
int main() {
print_x(); // Calling function from file1.c
x = 20; // Modifying the external variable from file1.c
print_x(); // Calling function again to print the updated value of x
return 0;
}
Cont.
• Internal Linkage:
○ Functions or variables with internal linkage are restricted to the current
source file. They cannot be accessed or referenced by other source files or
modules.
○ This is achieved by using the static keyword, which makes the function or
variable local to the file it is declared in.
example.
• Internal Linkage:
• file1.c (with internal linkage) • file2.c (won't work with internal linkage)
#include <stdio.h> #include <stdio.h>
// Internal linkage: static makes x and print_x() #include "file1.h" // Don’t header is useless for
visible only in this file internal linkage in file1.c
static int x = 10;
static void print_x() { int main() {
printf("x = %d\n", x); print_x(); // Linker error: print_x() has internal
linkage and can't be accessed here
}
return 0;
int main() {
}
print_x();
return 0;
}
Standard C library
• The Standard C Library is a collection of pre-written functions, macros, and types
that provide a wide range of functionality for C programming.
• The C Standard Library allows programmers to perform common tasks such as
input/output operations, memory management, string manipulation,
mathematical calculations, and more, without having to write these operations
from scratch.
• To use any of the functions from the C Standard Library, you need to include the
appropriate header files at the beginning of your program. The header files
contain the function declarations, so the compiler knows how to link the functions
correctly.
Most of the content after this have been discussed
in programming 1 and in chapter 2 of programming
2
Cont.
• Some of the standard libraries that we are going to see are the following
○ Input/output
○ String handling functions
○ Math functions
○ And some other standard C functions
Input/output
• Input/Output (I/O) refers to the process of receiving data from the user (input)
and displaying data to the user (output). This is a fundamental part of most
programs, allowing interaction with the user.
• Types of I/O in C:
○ Standard Input (stdin): Refers to data entered by the user (usually from the
keyboard).
○ Standard Output (stdout): Refers to data that is printed or output to the user
(usually to the screen).
○ Standard Error (stderr): Refers to error messages printed to the screen, often
used for debugging.
cont.
• Some functions of the input/output library
○ printf() - Used to print output.
○ scanf() - Used to read input from the user.
○ getchar() - Reads a single character from the keyboard.
○ putchar() - Writes a single character to the console.
• Example:
int main() {
int x;
printf('Enter an integer: ');
scanf('%d', &x);
printf('You entered: %d', x);
return 0;
}
String handling functions
• String handling functions are used for manipulating strings (arrays of characters).
The C Standard Library provides a variety of functions for working with strings,
including functions for copying, concatenating, comparing, and searching strings,
among others.
• The C library provides string manipulation functions like:
a. strlen() - Returns the length of a string.
b. strcpy() - Copies a string to another.
c. strcat() - Concatenates two strings.
d. strcmp() - Compares two strings.
• Example:
char str1[] = 'Hello';
char str2[] = 'World';
printf('%s', strcat(str1, str2)); // Output:
HelloWorld
Math functions
• Functions in the math.h header file for performing common mathematical
operations, such as trigonometric functions, logarithms, power, and others. Here
are some of the most commonly used math functions.
• Math functions provided by the standard library include:
a. abs() - Returns the absolute value of an integer.
b. pow() - Calculates the power of a number.
c. sqrt() - Calculates the square root of a number.
d. sin(), cos(), tan() - Trigonometric functions.
• Example
int result = abs(-5); // Output: 5
double result = pow(2, 3); // Output: 8.0
Other standard C functions
• Other functions available in the standard C library include dynamic memory
allocation functions, the exit function for terminating programs, and functions for
calculating the length of strings or arrays, among others.
• example
char *ptr = malloc(100 * sizeof(char));
free(ptr);
● example 2
char str[] = "Hello, world!";
int length = strlen(str);