Chapter 5: C Libraries
A C library is a collection of precompiled functions and definitions that you can use to add functionality to your programs. To program efficiently in C, you need to know how to use these libraries and how to create your own.
5.1 Standard library functions
The C Standard Library has functions for input/output, string manipulation, mathematical computation, and more. Some of the most commonly used ones follow.
5.1.1 String handling
The functions for handling strings are in the <string.h> library.
Common functions:
strlen: Returns the length of a string.strcpy: Copies one string to another.strcat: Concatenates two strings.strcmp: Compares two strings.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[20] = "World";
char str3[20];
// Copy str1 to str3
strcpy(str3, str1);
printf("strcpy: %s\n", str3);
// Concatenate str1 and str2
strcat(str1, str2);
printf("strcat: %s\n", str1);
// Length of str1
printf("strlen: %zu\n", strlen(str1));
// Compare str1 and str2
int cmp = strcmp(str1, str2);
printf("strcmp: %d\n", cmp);
return 0;
}
5.1.2 Mathematical functions
Mathematical functions are available in the <math.h> library.
Common functions:
sqrt: Computes the square root.pow: Raises a number to a power.sin,cos,tan: Trigonometric functions.fabs: Computes the absolute value of a floating-point number.
Example:
#include <stdio.h>
#include <math.h>
#define PI 3.14159265358979323846
int main() {
double num = 16.0;
printf("Square root of %.2f: %.2f\n", num, sqrt(num));
printf("2 raised to the power 3: %.2f\n", pow(2, 3));
printf("Sine of 45 degrees: %.2f\n", sin(45 * PI / 180)); // Convert degrees to radians
return 0;
}
Standard C has no constant for π. Many systems define M_PI in <math.h>, but that comes from POSIX, not the C standard, so the example defines its own PI. On Linux you also have to link the math library by adding -lm at the end of the command, as in gcc math_example.c -o math_example -lm. On macOS the math functions are part of the standard C library, so -lm is optional there.
5.1.3 Time and date functions
For time and date functions, use the <time.h> library.
Common functions:
time: Returns the current time.ctime: Converts time to a string.difftime: Computes the difference between two times.strftime: Formats date and time.
Example:
#include <stdio.h>
#include <time.h>
int main() {
time_t current_time;
time(¤t_time);
printf("Current time: %s", ctime(¤t_time));
return 0;
}
5.2 Writing and using header files
A header file declares functions and variables so that several source files can share them. Header files usually have a .h extension.
To create a header file:
- Create a file named
myheader.h. - Declare functions and variables in it.
myheader.h:
// Function prototype
void greet();
To use the header file, include it in your source file with #include.
main.c:
#include <stdio.h>
#include "myheader.h"
// Function definition
void greet() {
printf("Hello from the header file!\n");
}
int main() {
greet();
return 0;
}
Explanation:
#include "myheader.h"includes the header file.- The
greetfunction is declared in the header file and defined in the source file.
5.3 Linkers and makefiles
Linkers and makefiles are essential for managing larger C projects. The linker combines several object files into a single executable, and a makefile automates the build process.
5.3.1 Using the linker
When you compile several source files, the linker can combine them into a single executable.
Example:
- Create two source files,
file1.candfile2.c.
file1.c:
#include <stdio.h>
void function1() {
printf("This is function1 from file1.\n");
}
file2.c:
void function1();
int main() {
function1();
return 0;
}
- Compile and link the files:
gcc -c file1.c
gcc -c file2.c
gcc file1.o file2.o -o myprogram
./myprogram
Explanation:
gcc -c file1.ccompilesfile1.cinto an object filefile1.o.gcc -c file2.ccompilesfile2.cinto an object filefile2.o.gcc file1.o file2.o -o myprogramlinks the object files into an executablemyprogram.
5.3.2 Writing a makefile
A makefile automates the build by spelling out how to compile and link the program.
Example Makefile:
# Makefile for building myprogram
# Compiler
CC = gcc
# Compiler flags
CFLAGS = -Wall
# Target executable
TARGET = myprogram
# Source files
SRCS = file1.c file2.c
# Object files
OBJS = $(SRCS:.c=.o)
# Build the target
$(TARGET): $(OBJS)
$(CC) $(CFLAGS) -o $(TARGET) $(OBJS)
# Compile source files into object files
%.o: %.c
$(CC) $(CFLAGS) -c $< -o $@
# Clean up object files and executable
clean:
rm -f $(OBJS) $(TARGET)
Each command line under a rule (the recipe) must start with a tab character. Make rejects lines indented with spaces, with an error such as missing separator.
Explanation:
CC = gccsets the compiler togcc.CFLAGS = -Wallturns on most of the common compiler warnings. Despite the name it doesn’t enable every warning;-Wextraadds more.TARGET = myprogramsets the name of the executable.SRCS = file1.c file2.clists the source files.OBJS = $(SRCS:.c=.o)converts source file names to object file names.$(TARGET): $(OBJS)defines the target and its dependencies.$(CC) $(CFLAGS) -o $(TARGET) $(OBJS)links the object files to create the executable.%.o: %.ccompiles each source file into an object file.clean:removes the object files and executable.
Building with Make:
make
./myprogram
make clean
Explanation:
makecompiles and links the program../myprogramruns the executable.make cleanremoves the object files and executable.