What are C Library Functions Explained- Best C Language Course For Beginners

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

C Library Functions Explained
Free C tutorial for embedded developers: Chapter 6, Lecture 2. Understand C library functions, header files and the linker before you write your own.

C Library Functions: Ready-Made Building Blocks

Before you write a single function of your own, you already use dozens of them. Every time you call printf, strlen or sqrt you are using C library functions that someone else wrote, tested and shipped with your compiler. This lecture of our free C programming course explains how C library functions work, why they need header files, and what changes when the same code runs on a microcontroller instead of a laptop. It is a core step in any free embedded C course because firmware leans on the standard library more than most beginners expect.

What You Will Learn

  • What C library functions are and where their code actually lives
  • How #include brings in declarations through header files
  • Which header provides which group of functions
  • Why math functions sometimes need the -lm linker flag
  • How library usage differs in embedded C programming on bare-metal targets
  • How to read a library function prototype with confidence

Prerequisites

Complete Lecture 1 of this chapter first, and make sure you can compile a small C file with GCC. You should also recall the basic data types int, double and char.

What Are C Library Functions?

The C standard defines a collection of functions that every conforming compiler must provide. They are already written and compiled into a library file. Your program does not contain their source code; it only contains calls to them. The linker later connects each call to the real code. Because the functions are predefined, you save time and benefit from years of testing by thousands of users.

Typical groups include input and output (printf, scanf), string handling (strlen, strcmp, strcpy), mathematics (sqrt, pow, fabs), character tests (isdigit, toupper) and memory or utility routines (malloc, abs, atoi).

Header Files: The Menu of Available Functions

When you call a function, the compiler wants to know its name, the types of its parameters and the type it returns. That information is called a declaration or prototype, and header files carry it. Writing #include <math.h> tells the preprocessor to paste the declarations for the math group into your file before compilation begins.

A header contains declarations only. The actual machine code is elsewhere, inside the library that the linker uses. Forgetting the header is a classic error: the compiler may guess the wrong return type, and the program can print nonsense without any obvious warning on older settings.

HeaderPurposeSample functions
stdio.hInput and outputprintf, scanf, puts
math.hMathematicssqrt, pow, fabs, sin
string.hStrings and memory blocksstrlen, strcmp, memcpy
ctype.hCharacter classificationisalpha, isdigit, tolower
stdlib.hUtilities and memoryabs, atoi, malloc, exit

From Source to Executable: Where Library Code Joins

Understanding the build flow removes a lot of mystery. Your source file passes through the preprocessor, which handles includes. The compiler turns it into an object file with unresolved references to library functions. Finally the linker searches the library, finds the machine code for each referenced function, and combines everything into one executable.

How a library function reaches your program
1. Source file
your code + #include
2. Preprocessor
pastes header prototypes
3. Compiler
object file with open references
4. Linker
resolves calls using the library
5. Executable
ready to run or flash

Worked Example: Magnitude of a Two-Axis Reading

Imagine a two-axis accelerometer that reports a sideways value and a forward value. The overall strength of the motion is the square root of the sum of their squares. We will compute it with C library functions from math.h and show the result with printf.

#include <stdio.h>
#include <math.h>

int main(void)
{
    double side = 3.0;
    double fwd  = 4.0;

    double magnitude = sqrt(pow(side, 2.0) + pow(fwd, 2.0));

    printf("side=%.1f forward=%.1f\n", side, fwd);
    printf("magnitude = %.2f\n", magnitude);
    return 0;
}

Build and run on Linux. Many toolchains need the math library to be linked explicitly:

gcc -Wall -o ep_accel ep_accel.c -lm
./ep_accel
side=3.0 forward=4.0
magnitude = 5.00

Reading the Example Line by Line

Two headers are included: one for printf and one for sqrt and pow. The variables are double because the math functions work on doubles. The expression inside sqrt calls pow twice, so a library function can take another library function’s result as its argument. Finally printf prints the answer with two digits after the decimal point.

Second Example: Using String Library Functions

#include <stdio.h>
#include <string.h>

int main(void)
{
    const char *cmd = "START";

    printf("length  : %zu\n", strlen(cmd));
    printf("is START: %s\n", strcmp(cmd, "START") == 0 ? "yes" : "no");
    return 0;
}
length  : 5
is START: yes

Here strlen counts characters before the terminating null, and strcmp returns zero when two strings are equal. Comparing the return value with zero is a very common pattern in command parsers for UART-based firmware.

How to Read a Function Prototype

A prototype such as double sqrt(double x); packs everything you need. The word before the name is the return type, the name identifies the function, and the parenthesized list gives parameter types. When you meet an unfamiliar library routine, read its prototype first and the manual page second. On Linux, man 3 sqrt opens the reference in your terminal.

Anatomy of a prototype
Return type
double
Function name
sqrt
Parameter list
double x

C Library Functions in Embedded Systems

On a bare-metal microcontroller there is no operating system, so the standard library is usually a compact implementation such as newlib or newlib-nano that ships with the ARM GCC toolchain. Several points differ from desktop work:

  • Size: printf with floating-point support can add many kilobytes of flash. Many projects choose a lightweight formatting routine instead.
  • Retargeting: printf needs a low-level output hook so characters reach your UART rather than a screen.
  • Heap use: malloc may be forbidden by project rules because fragmentation is risky on long-running devices.
  • Floating point: math functions can be slow without a hardware FPU, so integer alternatives are common.
ConcernDesktopMicrocontroller
printf outputTerminal, automaticNeeds UART or debug retargeting
Library sizeIrrelevantDirectly consumes flash
mallocEveryday useOften avoided
Math speedFast FPUMay be software emulated

Common Mistakes with C Library Functions

  1. Missing header. Include the header that matches each function you call.
  2. Missing -lm. An “undefined reference to sqrt” message at link time usually means the math library was not linked.
  3. Wrong type in printf. Using %d for a double prints garbage.
  4. Ignoring return values. Functions such as scanf report how many items they read.
  5. Assuming the library is free. Each function you link costs flash on a small device.

Best Practices and Security Notes

Do this

  • Include only the headers you need, which keeps builds tidy.
  • Prefer bounded functions such as snprintf over unbounded ones.
  • Check return values for anything that can fail.
  • Measure the flash cost of a library function before adopting it in firmware.
Security: Unbounded routines like gets and careless use of strcpy are classic sources of buffer overflows. Always know the size of the destination buffer.

Summary and Key Takeaways

  • C library functions are predefined, tested and delivered with the compiler.
  • Header files declare them; the linker supplies their machine code.
  • Each group of functions has its own header, such as stdio.h or math.h.
  • Math routines may require -lm when linking.
  • In embedded C programming the library is smaller, must be retargeted, and costs flash.

With library functions understood, you are ready to write your own. The next lecture introduces user-defined functions and the three ideas that go with them: definition, declaration and call.

Frequently Asked Questions

Why do I need a header file if the library already exists?

The header tells the compiler the function’s signature. The library only provides the compiled code for the linker.

What does “undefined reference to sqrt” mean?

The linker could not find the math library. Add -lm at the end of the compile command.

Can I use printf on a microcontroller?

Yes, after retargeting its low-level output to a UART or debug interface, though it may use a lot of flash.

Are library functions part of the C language?

They are part of the C standard library, defined by the language standard but separate from the core syntax.

Is it safe to use strcpy?

Only when you are certain the destination is large enough. Bounded alternatives are safer.

How can I see a function’s documentation?

On Linux use man 3 function_name, for example man 3 strlen.

Does this free C programming course cover embedded targets?

Yes. Each lecture ties the language feature back to embedded C programming practice.

Keep Learning C for Embedded Systems

Move on to user-defined functions and keep building your free embedded C course skills one lecture at a time.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →