Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.
C Library Functions Explained
Lecture 21 of our free C programming course: how precompiled library functions in C are declared, linked and used in embedded C programming.
Welcome back to the free C programming course on EmbeddedPathashala. In this lecture of our free C tutorial we study library functions in C: the ready-made routines such as printf(), strlen() and sqrt() that ship with every compiler. If you want to learn embedded C programming, you will call library functions in almost every file you write, so it is worth knowing exactly where they live and how they reach your program.
Many beginners treat printf() as if it were part of the language. It is not. The C language itself only defines keywords, operators and statements. Everything else is provided by the standard library, and your toolchain stitches that library into your firmware at link time. This lecture is part of our free embedded C course, and it explains that stitching process step by step.
What You Will Learn
- What library functions in C are and why they are not part of the language itself
- How the compiler, the header file and the linker cooperate to make a library call work
- Who writes the definition, the declaration and the call for a library function, a user function and
main() - The four facts you must know before using any library function
- Why linking with
-lmis sometimes required, shown with a real linker error - What happens when you define your own function with a standard library name
- How library functions behave in embedded C programming on microcontrollers
Prerequisites
Before you start
- You have finished the earlier lectures of this chapter on function declaration, definition and call.
- You can compile a small program with
gccon Linux, or an equivalent compiler on your own machine. - You know what a header file and the
#includedirective do at a basic level.
What Are Library Functions in C?
Library functions in C are functions that were written, tested and compiled by someone else, then packaged so that every programmer can reuse them. They are formally not a part of the C language. The language standard describes them, and every conforming compiler distribution supplies them, but they are separate from keywords such as if or while.
Two properties define a library function. First, you normally do not receive its source code. You receive precompiled object code that has already been translated into machine instructions for your target processor. Second, related functions are grouped into library files. String routines, math routines, character tests and input-output routines each live in their own logical group, even though a toolchain may physically pack several groups into one archive file.
Key idea
A library function is already compiled. Your compiler only needs to know its shape (name, argument types and return type). The real machine code is added later by the linker.
How a Library Call Reaches Your Program
The path from your source file to a running program has several stages, and the library takes part in two of them. During compilation the header file tells the compiler what each function looks like. During linking the linker finds the actual code inside the library file and copies it into your executable.
Source file
You write a call such as strlen(tag) in your .c file and add #include <string.h> at the top.
Compiler
The header gives the compiler the declaration. It checks the argument and return types, then leaves a placeholder for the real address.
Object file
Your code is now machine code with an unresolved reference to strlen.
Linker
The linker searches the library file, selects only the code for the functions you called and adds it to your program.
Executable
A complete program image that contains your code plus the borrowed library code.
Notice that the linker selects only the code it needs. If your program calls strlen() but never calls strcpy(), a typical linker leaves strcpy() out of the final image. On a microcontroller with a few kilobytes of flash this selective linking is very important.
Definition, Declaration and Call: Who Does What?
Every function has three roles attached to it: the definition (the body), the declaration (the shape announced to the compiler) and the call (the place where it is used). The table below compares who is responsible for each role for the three kinds of function you meet most often.
| Role | Library function | User-defined function | main() |
|---|---|---|---|
| Definition | Already written, compiled and stored in the library | You write it | You write it |
| Declaration | Supplied by a header file (a .h file) | You write a prototype or define it before use | No prototype is needed, the startup code knows the entry point |
| Call | You write the call in your code | You write the call in your code | The startup code, run by the operating system or the reset handler, calls it |
The last column deserves a closer look. On a desktop system the operating system loads your program and a small piece of startup code calls main(). On a bare-metal microcontroller there is no operating system. The processor starts at its reset vector, the reset handler prepares memory and then calls main(). In both cases you never write the call yourself, and a value returned from main() is simply handed back to whoever started the program.
Definition
Library: the vendor of the compiler. User function: you. main: you.
Declaration
Library: header file. User function: your prototype. main: nothing required.
Call
Library: you. User function: you. main: the startup code.
Four Facts You Need Before Using a Library Function
To use any library function correctly you should know the following four things. Treat them as a checklist whenever you meet a new function in a datasheet, a man page or a code review.
- Name and purpose. For example,
strlenreturns the length of a string. - Type and number of arguments.
strlentakes exactly one argument, a pointer to a character string. - Type of the returned value.
strlenreturns a value of typesize_t, an unsigned integer type. - Header file to include.
strlenis declared in<string.h>.
If you skip the fourth fact, the compiler has no declaration and may assume the function returns int. That assumption is wrong for functions that return double or a pointer, and the bug appears only at run time. Modern compilers treat a missing declaration as an error in recent language modes, so always include the right header.
Hands-On: Calling Library Functions in C
Here is a small program that uses three library functions from three different headers. Read it first, predict the output, then compile it.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
int main(void)
{
const char *tag = "sensor";
double area = 4.0;
printf("strlen(\"%s\") = %zu\n", tag, strlen(tag));
printf("sqrt(%.1f) = %.1f\n", area, sqrt(area));
printf("toupper('q') = %c\n", toupper('q'));
return 0;
}
Output:
strlen("sensor") = 6
sqrt(4.0) = 2.0
toupper('q') = Q
Compile it with the math library listed explicitly:
gcc -std=c11 -Wall -Wextra -o lib_demo lib_demo.c -lm
./lib_demo
The flag -lm tells the linker to search the math library. On many Linux systems the functions of <stdio.h>, <string.h> and <ctype.h> live in the default C library, which is always searched, while the functions of <math.h> are kept in a separate library that must be requested.
What happens if you forget -lm
The next program feeds sqrt() a value that is known only at run time, so the compiler cannot replace the call with a constant. We compile it without -lm on purpose:
Program lib_nolm.c compiled without -lm
#include <stdio.h>
#include <math.h>
int main(int argc, char **argv)
{
double v = (double)argc * 16.0;
(void)argv;
printf("%.1f\n", sqrt(v));
return 0;
}
Output:
/usr/bin/ld: in function `main':
lib_nolm.c:(.text+0x37): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status
Look carefully at who is complaining. The message comes from ld, the linker, not from the compiler. The compiler was perfectly happy because <math.h> declared sqrt(). The linker could not find a definition. An undefined reference error always means that a declaration exists but no definition was supplied.
Compiler error
Typical wording: implicit declaration, conflicting types, too few arguments. It means the declaration is missing or does not match the call.
Linker error
Typical wording: undefined reference. It means the declaration was fine but no definition (library or object file) was linked in.
Library Functions in Embedded C Programming
In embedded C programming the story has a few extra twists. A microcontroller toolchain usually ships a compact C library, often derived from newlib or a vendor variant, built for small flash and RAM sizes. A few points are worth remembering when you apply library functions in C to firmware.
| Topic | Desktop program | Embedded firmware |
|---|---|---|
| Library size | Large, shared between programs | Compact, copied into your image |
printf() output | Goes to the terminal automatically | You must connect it to a UART or semihosting channel yourself |
malloc() | Operating system manages memory | Often avoided or limited because RAM is tiny |
| Floating point | Hardware FPU almost always present | May be emulated in software, which is slow and large |
| Startup | OS calls main() | Reset handler calls main() |
Because every kilobyte matters, embedded engineers often count the cost of a library function before calling it. A single call to printf() with floating-point formatting can pull in several kilobytes of code. Knowing that library code is copied into your image is what lets you reason about this cost.
Defining Your Own Function With a Library Name
The C book you may be reading states that if you define a function with the same name as a library function, your definition takes precedence. That statement is partly true but dangerous, so let us test it. Here is a program that defines its own abs():
Program own_abs.c
#include <stdio.h>
#include <stdlib.h>
int abs(int x)
{
puts("[my abs called]");
return x < 0 ? -x : x;
}
int main(void)
{
printf("%d\n", abs(-7));
return 0;
}
Compiled normally with GCC 13 the program printed only the value 7. The message from our function never appeared, because the compiler knows abs() as a built-in and replaced the call with a constant. Compiled again with -fno-builtin the output became:
[my abs called]
7
So the same source gave two different behaviours depending on a compiler flag. The C standard reserves the names of standard library functions, so redefining one with external linkage is not something you can rely on. The safe habit is to give your own functions a project prefix, or to mark them static:
#include <stdio.h>
static int ep_abs(int x)
{
return x < 0 ? -x : x;
}
int main(void)
{
printf("%d\n", ep_abs(-7));
return 0;
}
Output:
7
Common Library Function Groups
| Header | What it gives you | Example functions |
|---|---|---|
<stdio.h> | Input and output | printf, scanf, puts |
<string.h> | String and memory block handling | strlen, memcpy, memset |
<math.h> | Mathematics | sqrt, pow, fabs |
<ctype.h> | Character classification | isdigit, toupper |
<stdlib.h> | General utilities | abs, atoi, malloc |
You will meet each of these groups in detail in later chapters of this free embedded C course. For now, notice the pattern: one header per group, and the header carries only declarations, never the code.
Common Mistakes and Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Warning or error: implicit declaration of function | You forgot the header file | Add the correct #include |
| undefined reference to a math function | Math library not linked | Add -lm at the end of the command |
| Strange return values from a library call | Wrong or missing declaration, so the compiler guessed int | Include the header and compile with -Wall -Wextra |
| Your function is ignored | Same name as a built-in library function | Rename it with a prefix or make it static |
| Firmware too large | Heavy library routines such as formatted floating-point output | Use lighter alternatives or a smaller C library variant |
Best Practices, Performance and Security
Best practices
- Include the header for every library function you call, even if the program seems to work without it.
- Compile with
-Wall -Wextraso that missing declarations are reported. - Prefix your own functions or use
staticto avoid clashing with library names. - Check the return value of library functions that can fail.
Performance considerations
Library routines are usually well optimised, and for tasks such as copying memory they are often faster than a hand-written loop. Still, a call has a cost, and in a tight interrupt handler you should check whether a simple expression does the job without a call.
Security considerations
Some classic library functions do not check buffer sizes. Calling strcpy() or gets() with unchecked input is a well-known source of buffer overflows. Prefer bounded variants, validate lengths first and never trust data that arrives from a network or a serial port.
Summary and Key Takeaways
Remember
- Library functions are not part of the C language. They come precompiled with your compiler distribution.
- The header supplies the declaration, the library file supplies the definition and the linker joins them.
- An undefined reference is a linker problem, while an implicit declaration is a compiler problem.
main()is called by startup code, not by your own code.- Do not reuse standard library names for your own functions.
Conclusion
You now know where library functions in C come from and how they travel from a header file and a library archive into your finished program. This understanding pays off the first time a linker prints an undefined reference at midnight before a release, and it helps you judge code size on a small microcontroller. The next lecture in our free C programming course looks at an old way of writing function headers that you will still meet in legacy code.
Frequently Asked Questions
Are library functions part of the C language?
No. The language defines keywords, operators and statements. Library functions are supplied separately with every compiler as precompiled code.
Why do I get an undefined reference to sqrt?
The header declared sqrt() so the compiler was satisfied, but the linker did not search the math library. Add -lm to the link command.
Can I see the source code of printf?
Not from your compiler distribution in normal use. You receive object code only, although open source C libraries such as newlib or glibc publish their sources separately.
What is the difference between a header file and a library file?
A header file holds declarations for the compiler. A library file holds compiled definitions for the linker.
Who calls main() in a microcontroller program?
The reset handler and startup code run after power-up and then call main(). There is no operating system involved.
Is it safe to name my function the same as a library function?
No. Behaviour can change with compiler flags because the compiler may treat the name as a built-in. Use a prefix or static.
Is this a free embedded C course for beginners?
Yes. EmbeddedPathashala offers this free C programming course so that students can learn C programming for embedded systems without paying anything.
Keep Going With the Free Embedded C Course
Next we study the old K&R style of declaring and defining functions, a style you still meet in legacy firmware.
Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments