Module 0 · Lesson 29 of 42

static, extern, and libraries

Control linkage with static and extern, and build and link static and shared libraries by hand.

  • Beginner to advanced
  • 9 min read
  • 24 min lab
What you will need

gcc, make and binutils on Ubuntu 24.04 (WSL2, VM or container); no special hardware needed

Your place in the module
By the end you can 3 objectives
  • Use extern to share a global and static to hide one, and predict the linkage of each file-scope name.
  • Build a multi-file program by hand, create a static library with ar, and link it with -L and -l in the correct order.
  • Compare static and shared libraries and state when each is resolved and used.
Video coming soonstatic, extern, and libraries
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Multi-file programs and the linker
  • Each .c file is a translation unit compiled alone into an object file; the linker stitches them and resolves symbols.
  • A declaration announces a name; a definition also reserves storage, and each name may have exactly one definition.
  • Headers carry declarations and include guards, never variable definitions, and each file includes only what it uses.
01

static and extern: linkage and lifetime

4 min read

The previous lesson showed how files compile into objects and the linker stitches them into one program. This lesson answers how static and extern control which names cross file boundaries, and what .a and .so libraries are.

Two keywords control how a name crosses file boundaries, and one of them does double duty. is the concept, and extern and static are the switches.

A file-scope name is external by default, visible to every other file, and has external linkage. A function int sensor_read(void) { ... } can be called from anywhere, and a global int samples_taken; can be read from anywhere, provided the other file declares them. Adding static to a file-scope name gives it internal linkage: the name is private to its own translation unit and invisible everywhere else, even if another file declares it extern.

c
/* sensor.c */
int samples_taken = 0;          /* external linkage, shared */

static int last_reading;        /* internal linkage, private to sensor.c */

static int read_adc(void)       /* internal linkage, a private helper */
{
    return 0; /* placeholder */
}

int sensor_read(void)
{
    last_reading = read_adc();
    samples_taken++;
    return last_reading;
}

Here samples_taken and sensor_read are part of the module's public surface, while last_reading and read_adc are private implementation details. This is information hiding: the internal names cannot collide with names in other files, and other files cannot accidentally use or change them. It also helps the compiler optimize, because it knows a static function is not called from outside its own file.

extern goes the other way. Writing extern int samples_taken; in a header declares the variable without defining it, so every file that includes the header shares the single definition in sensor.c. On a function, extern is the default and is redundant; int sensor_read(void); already has external linkage.

The word static has a second, unrelated meaning inside a function. A static local variable has static storage duration: it is initialized once, at program startup, and its value persists between calls, unlike an ordinary local, which is recreated on every call. This is the same keyword but a different property; it has nothing to do with linkage.

c
unsigned next_sequence(void)
{
    static unsigned n = 0;   /* initialized once, survives between calls */
    return n++;
}
Internal versus external linkagestatic(internal)external(default)Visible fromother filesnoyesApplies tofunctions andglobalsfunctions andglobalsShared acrossfilesno, privatecopyyes, oneobjectExamplestatic intlast_reading;int samples_taken;
static gives internal linkage and a persistent local, while the default and extern give external linkage
Going deeperTentative definitions

A file-scope declaration without an initializer, such as int samples_taken;, is a tentative definition. Within one translation unit it acts as a declaration, and if that file has no definition with an initializer, it becomes the definition, initialized to zero. Across files, the standard says two such definitions break the one-definition rule. Older GCC (before version 10) placed them in a "common" section and quietly merged them into one object, so legacy code that defines int samples_taken; in a header used to link. Since GCC 10 the default is -fno-common, and Ubuntu 24.04's gcc reports multiple definition of 'samples_taken'. A definition with an initializer, int samples_taken = 1;, was always a hard error when duplicated. The portable habit is to write extern in the header and a single definition, with or without an initializer, in one .c file, so the intent is explicit and the merge never happens by accident.

The embedded angle matters here too. A driver or board-support file is full of private static helpers and one public surface, and keeping the surface small is what lets the compiler and the build system manage a large tree without symbol collisions between independently written drivers.

static hides names: read the symbol table with nm
learner@embeddex:~/lab$ # compile the module that owns both public and private names
learner@embeddex:~/lab$ gcc -c sensor.c
learner@embeddex:~/lab$ # uppercase T and B are global; lowercase t and b are static, private to
 this file
learner@embeddex:~/lab$ nm sensor.o
0000000000000004 b last_reading
0000000000000000 t read_adc
0000000000000000 B samples_taken
000000000000000f T sensor_read
learner@embeddex:~/lab$ # main.c declares read_adc extern, so it compiles
learner@embeddex:~/lab$ gcc -c main.c
learner@embeddex:~/lab$ # but the linker cannot see the static function at all
learner@embeddex:~/lab$ gcc -o demo main.o sensor.o
/usr/bin/ld: main.o: in function `main':
main.c:(.text+0x9): undefined reference to `read_adc'
collect2: error: ld returned 1 exit status
02

Building by hand: objects, linking and static libraries

4 min read

Everything gcc does behind the scenes can be done step by step, and doing it once by hand is how you learn what make will automate. The -c flag means compile only, do not link, producing an object file for each source.

bash
gcc -c main.c        # produces main.o
gcc -c sensor.c      # produces sensor.o
gcc -c stats.c       # produces stats.o
gcc -o monitor main.o sensor.o stats.o

The last line links the three objects into the executable monitor. The power of this split is incremental rebuild: edit only stats.c, and you recompile only stats.c, then relink. The other two objects are reused untouched, which is what makes a large project buildable in reasonable time.

A packages a set of objects for reuse. The ar tool builds one, and the r, c and s flags mean replace, create and index.

bash
gcc -c stats.c
ar rcs libstats.a stats.o

The archive is now a self-contained unit. To link a program against it you use -L to add a directory to the search path and -l to name the library, where -lstats means the file libstats.a or libstats.so.

bash
gcc -o monitor main.o sensor.o -L. -lstats

-L. tells the linker to look in the current directory, and -lstats resolves to libstats.a. Order matters here, and it is the single most common link error. The traditional linker scans its inputs from left to right, and when it reaches a static archive it pulls in only those members that satisfy a symbol that is still undefined at that moment. So the objects that reference a library must come before the -l that provides it.

bash
gcc -lstats -o monitor main.o sensor.o   # wrong: main.o comes after, symbols not yet known

The math library is the example everyone meets first. On glibc, functions such as sin, cos and pow live in a separate library, libm, so you must name it with -lm, and it must come after the objects that use it.

bash
gcc -o monitor main.o sensor.o stats.o -lm
Building and linking a static librarygcc -c stats.cstats.oobject filear rcs libstats.astats.olibstats.aarchivegcc -o monitormain.o sensor.o-L. -lstatsmonitorgcc -c stats.cstats.oobject filear rcs libstats.a stats.olibstats.aarchivegcc -o monitor main.osensor.o -L. -lstatsmonitor
Compiling objects, archiving them into libstats.a, then linking with -L and -l

1compile each source

Run gcc -c on every .c file to produce one .o per translation unit.

2archive if you reuse the code

Run ar rcs to package several .o files into a static library.

3link

Run gcc with the objects and libraries, objects before libraries.

4read the errors

Treat every undefined reference and multiple definition as information about what is missing or duplicated.

On musl the math library is folded into libc

The glibc behaviour above is the default on Ubuntu. On musl, a smaller C library common on embedded Linux, the math functions are part of libc, so -lm is an empty stub. When you move a build to an embedded target, do not assume library names and splits are identical; they are a property of the C library, not of the language.

Build a static library and link it in the right order
learner@embeddex:~/lab$ # compile the module you will package as a library
learner@embeddex:~/lab$ gcc -c stats.c
learner@embeddex:~/lab$ # r, c and s: replace, create and index the archive
learner@embeddex:~/lab$ ar rcs libstats.a stats.o
learner@embeddex:~/lab$ # the archive holds the object file as a member
learner@embeddex:~/lab$ ar t libstats.a
stats.o
learner@embeddex:~/lab$ # objects first, then -L adds the directory and -l names the library
learner@embeddex:~/lab$ gcc -o monitor main.o sensor.o -L. -lstats
learner@embeddex:~/lab$ # links and runs
learner@embeddex:~/lab$ ./monitor
avg=20 reading=7
learner@embeddex:~/lab$ # library first: it is scanned before any symbol is undefined, so nothin
g is pulled
learner@embeddex:~/lab$ gcc -L. -lstats -o monitor main.o sensor.o
/usr/bin/ld: main.o: in function `main':
main.c:(.text+0x45): undefined reference to `average'
collect2: error: ld returned 1 exit status
03

Symbols, linkage and the .a versus .so split

3 min read

Every object file carries a symbol table: a list of the names it defines and the names it references. For each reference the linker must find exactly one definition, and the rules of linkage from the last section decide which names are even on the table. A static function or variable is recorded in its own object's symbol table only as a local symbol (a lowercase t or d in nm output), so the linker never uses it to satisfy another file's reference. This is why internal linkage is also a safety property: a private name cannot collide with anything.

The distinction between static and shared libraries is about when this resolution happens. A static archive, a .a, is resolved at link time: the linker copies the needed object code from the archive into your executable, and once built, the executable needs nothing external. A shared object, a .so, is resolved at load time: the executable records that it needs a library, and the dynamic linker, ld.so, loads the library and connects the symbols when the program starts. The full picture of ELF files and dlopen is a later module; here the important point is the split itself.

bash
gcc -c -fPIC stats.c
gcc -shared -o libstats.so stats.o       # build a shared library
gcc -o monitor main.o sensor.o -L. -lstats   # links against libstats.so

The two forms trade differently. Static linking makes the executable bigger, because the library code is copied in, but self-contained, which matters on an embedded target where you may not want to ship a full set of shared libraries. Shared linking keeps executables small and lets many processes share one copy of the code in memory, but the target must have the matching .so and a dynamic linker to load it. A small embedded root filesystem is exactly the place where this trade is decided deliberately, often with a mix: a static BusyBox for the essentials and shared libraries for the applications.

Static archive versus shared object.a static.so sharedResolvedat link timeat load timeIn theexecutablecopied inreferencedonlyBinary sizelargersmallerNeeds library ontargetnoyesBuilt withar rcsgcc -shared
Static archives are copied in at link time while shared objects are resolved at load time
Going deeperstatic inline in headers avoids duplicate symbols

A small function used in many files is sometimes written directly in a header. Defining it plainly there would violate the one-definition rule, because every including file gets a definition. Marking it static inline gives each translation unit its own internal-linkage copy, or lets the compiler inline the body away entirely, so no duplicate external symbol is emitted. This is how header-only utility code works. The trade is that a non-inlined static copy exists per file, so it is a technique for very small functions, not for a large implementation.

Going deeperLink order and the --start-group escape hatch

Because the linker pulls from an archive only to satisfy currently-undefined symbols, two archives that reference each other can be impossible to order correctly by hand. GNU ld offers -Wl,--start-group liba.a libb.a -Wl,--end-group, which repeatedly scans the group until no new symbol is resolved. This is a last resort for circular dependencies; the clean fix is to design modules so their dependency graph is acyclic, objects first, then libraries in dependency order.

Cross-compiling changes the variable, not the Makefile

Everything so far used the host compiler gcc. To build for an ARM board you cross-compile, and the only thing that changes is the compiler name: CC=arm-linux-gnueabihf-gcc make. The -c, -L and -l mechanics are identical, and the library you link is a cross-compiled archive, not a host one. Keeping the toolchain name in a variable is exactly why make exists, as the next sections show.

Key takeaways

  • extern declares a global defined elsewhere; static makes a file-scope name private and a function-scope name persistent.
  • A static library (.a) is an archive of objects copied in at link time; a shared library (.so) is resolved at load time.
  • Link order matters: put object files before the -l libraries, and -lm is a separate library on glibc.
  • A static name appears only as a local symbol in its object's table, so it cannot collide with names in other files.
Reflect
  1. Explain to a colleague, in two sentences: use extern to share a global and static to hide one, and predict the linkage of each file-scope name.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close