TExcelTAD
Home › Build Fundamentals: From Source to Binary › Link Errors & Link Order

Link Errors & Link Order

Compile errors point at a line of your code. Link errors point at symbols, often with no line number at all, which makes them feel mysterious. There are only a handful of kinds, and every one of them is reproduced on purpose below so you can recognise the message next time.

Undefined reference

The most common one: some object needs a symbol that no input defines. Usually a source file or library was left off the link line:

bash · try it yourself
mkdir -p le && cd le
cat > util.c <<'SRC'
int twice(int x) { return 2 * x; }
SRC
cat > main.c <<'SRC'
#include <stdio.h>
int twice(int x);
int main(void) { printf("%d\n", twice(21)); return 0; }
SRC
gcc -c util.c main.c
gcc main.o -o app
echo "exit status: $?"
gcc main.o util.o -o app && ./app
/usr/bin/ld: main.o: in function `main':
main.c:(.text+0xe): undefined reference to `twice'
collect2: error: ld returned 1 exit status
exit status: 1
42

Read the message from left to right: which object (main.o), which function in it (main), which symbol is missing (twice). collect2: error: ld returned 1 exit status is GCC's wrapper reporting that the linker failed; it is never the interesting line.

The same happens with system libraries that are not linked by default. The maths library is separate from the C library on glibc, so cos needs -lm:

bash · try it yourself
mkdir -p le && cd le
cat > wave.c <<'SRC'
#include <math.h>
#include <stdio.h>
int main(int argc, char **argv) {
    (void)argv;
    printf("%.3f\n", cos(argc * 0.5));
    return 0;
}
SRC
gcc -c wave.c
gcc wave.o -o wave
gcc wave.o -o wave -lm && ./wave
/usr/bin/ld: wave.o: in function `main':
wave.c:(.text+0x33): undefined reference to `cos'
collect2: error: ld returned 1 exit status
0.878

(The argument depends on argc so the compiler can't compute cos at compile time and remove the call; with a constant argument, GCC folds it and the bug hides until someone changes the code.)

Multiple definition

The opposite problem: two objects both define the same global symbol. The classic cause is a variable defined in a header instead of only declared there:

bash · try it yourself
mkdir -p le && cd le
cat > config.h <<'SRC'
int verbose = 0;          /* a definition: wrong in a header */
SRC
printf '#include "config.h"\nvoid log_init(void) { verbose = 1; }\n' > log.c
printf '#include "config.h"\nvoid log_init(void);\nint main(void) { log_init(); return verbose ? 0 : 1; }\n' > main.c
gcc -c log.c main.c
gcc log.o main.o -o app
echo "--- fixed header"
printf 'extern int verbose;       /* a declaration */\n' > config.h
printf 'int verbose = 0;\n' > config.c
gcc log.c main.c config.c -o app && ./app && echo "verbose is on"
/usr/bin/ld: main.o:(.bss+0x0): multiple definition of `verbose'; log.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status
--- fixed header
verbose is on

The fix is the standard pattern: extern int verbose; in the header (a declaration, no storage), and exactly one .c file with the definition. Older GCC versions (before 10) accepted the broken version silently because of "common symbols"; GCC 10 changed the default to -fno-common, so old code sometimes breaks with this error after a compiler upgrade.

Link order matters for static libraries

The GNU linker reads its inputs once, from left to right. Object files are always included. From a static library (.a, the subject of the next lesson), it only takes members that define a symbol that is currently undefined. If the library comes before the object that needs it, nothing is undefined yet, so nothing is taken:

bash · try it yourself
mkdir -p le && cd le
printf 'int twice(int x) { return 2 * x; }\n' > util.c
printf '#include <stdio.h>\nint twice(int);\nint main(void) { printf("%%d\\n", twice(4)); return 0; }\n' > main.c
gcc -c util.c main.c
ar rcs libutil.a util.o
echo "--- library first"
gcc -L. -lutil main.o -o app
echo "--- library last"
gcc main.o -L. -lutil -o app && ./app
--- library first
/usr/bin/ld: main.o: in function `main':
main.c:(.text+0xe): undefined reference to `twice'
collect2: error: ld returned 1 exit status
--- library last
8

Rule: put libraries after the objects that use them, and a library after the libraries that use it. If libfoo calls into libbar, write -lfoo -lbar.

Circular dependencies between libraries

Sometimes two static libraries need each other. Depending on which symbols are needed when, one order may happen to work (the first link below) and a small change breaks it (the second). Either repeat a library, or wrap both in --start-group … --end-group, which makes the linker rescan the group until nothing new resolves:

bash · try it yourself
mkdir -p le && cd le
printf 'int b_part(int);\nint a_part(int x) { return x > 0 ? b_part(x - 1) + 1 : 0; }\n' > a.c
printf 'int a_part(int);\nint b_part(int x) { return x > 0 ? a_part(x - 1) + 10 : 0; }\n' > b.c
printf '#include <stdio.h>\nint a_part(int);\nint main(void) { printf("%%d\\n", a_part(3)); return 0; }\n' > main.c
gcc -c a.c b.c main.c
ar rcs liba.a a.o && ar rcs libb.a b.o
gcc main.o -L. -la -lb -o app && ./app
printf 'int b_extra(void);\nint b_part(int x) { return x > 0 ? b_extra() : 0; }\n' > b.c
printf 'int a_extra(void) { return 7; }\nint b_extra(void) { return 8; }\n' > a2.c
gcc -c b.c a2.c && ar rcs libb.a b.o && ar rcs liba.a a.o a2.o
echo "--- -la -lb"
gcc main.o -L. -la -lb -o app
echo "--- grouped"
gcc main.o -L. -Wl,--start-group -la -lb -Wl,--end-group -o app && ./app
12
--- -la -lb
/usr/bin/ld: ./libb.a(b.o): in function `b_part':
b.c:(.text+0x16): undefined reference to `b_extra'
collect2: error: ld returned 1 exit status
--- grouped
9

In the second build, liba.a is scanned when only a_part is needed, so the member that defines b_extra is not pulled in; later libb.a needs b_extra, but the linker never goes back. The group fixes it. A real circular dependency is a design smell (the two libraries are really one), but it happens in legacy code.

Note: shared libraries (.so) don't have this problem in the same way: the linker records the whole library. lld and mold also search static archives more forgivingly than GNU ld. Write the correct order anyway, because GNU ld is still the default on most Linux distributions.

Model: one left-to-right pass

This model implements GNU ld's archive rule and shows why the order changes the result:

js · try it yourself
const objects = { "main.o": { defines: ["main"], needs: ["twice"] } };
const archives = { "libutil.a": [{ member: "util.o", defines: ["twice"], needs: [] }] };

function link(order) {
  const defined = new Set(), undefinedSyms = new Set(), used = [];
  const add = (m) => {
    used.push(m.member ?? m.name);
    m.defines.forEach((s) => { defined.add(s); undefinedSyms.delete(s); });
    m.needs.forEach((s) => { if (!defined.has(s)) undefinedSyms.add(s); });
  };
  for (const item of order) {
    if (objects[item]) add({ name: item, ...objects[item] });
    else for (const m of archives[item])        // only members that resolve something pending
      if (m.defines.some((s) => undefinedSyms.has(s))) add(m);
  }
  return `${order.join(" ")} -> used [${used}] undefined [${[...undefinedSyms]}]`;
}
console.log(link(["libutil.a", "main.o"]));
console.log(link(["main.o", "libutil.a"]));
libutil.a main.o -> used [main.o] undefined [twice]
main.o libutil.a -> used [main.o,util.o] undefined []

Test yourself

gcc -L. -lutil main.o fails with undefined reference to 'twice', but gcc main.o -L. -lutil works. Why?

  1. -L must come last
  2. GNU ld scans inputs left to right and only takes archive members that resolve symbols already undefined
  3. main.o is corrupt
  4. The library is shared

What is the correct fix for a global variable defined in a header that two .c files include?

  1. Add -fcommon
  2. Declare it extern in the header and define it in exactly one .c file
  3. Make it const
  4. Link with --start-group

Which line of a GCC link error usually tells you the least?

  1. main.o: in function 'main'
  2. undefined reference to 'twice'
  3. collect2: error: ld returned 1 exit status
  4. They are all equally useful