Undefined reference to

Once you start compiling stuff on your own, you'll definitely run into error messages like

/tmp/d34dcat.o: In function `main':
/tmp/d34dcat.o(.text+0x1f): undefined reference to `do_x'

This means that your linker can't figure out where "do_x" is.

The most common reasons for this error is misspelling or forgetting to link to the correct library.

If your program depends on libxyz, you can tell the linker to find it by giving it the argument -lxyz, or you can directly supply it as an argument.

Say you have two files; main.o and util.o, you've probably gotten them by running something like

$ cc -c util.c main.c

In util.c you reference a function called do_x, and do_x is in libxyz.

To link it

$ cc -o myprogram util.o main.o -lxyz

Finding lost functions

The main problem with undefined reference errors is as usual to find stuff you've lost.

Say you get the following error

/tmp/d34dcat.o: In function `main':
/tmp/d34dcat.o(.text+0x1f): undefined reference to `initscr'

First we check if there's anything in the man pages for the function

$ man -k initscr

If we're so unlucky as to not get any results, we try to google it.

The first result that showed up for me was this, so from context we can see that it's part of {,n}curses, so the problem is easy to fix; link to {,n}curses.

Since we don't know which other libraries ncurses might depend on too, we can check with pkg-config

$ pkg-config --libs ncurses
-lncurses -ltinfo

The linking arguments are always placed last, as they are order sensitive.

$ cc -o myprogram *.o -lncurses -ltinfo