Tuesday, October 12, 2010

Link order of libraries - gcc: undefined reference to `func_in_lib'

This linker error
  program.c:(.text+0x212): undefined reference to `sqrt'
usually appears when a certain library (in this case libm) is missing. 

Some versions of gcc also produce this error even if the corresponding library (-lm) is present in the command line but in the incorrect order
  gcc -lm program.c -o program
the linker search for external functions from left to right in the files specified in the command line.
The correct order is to include the libraries after the source or object files that reference them:
  gcc program.c -lm -o program

Note that for simple examples, this issue may not appear. 
With gcc-4.4 I obtained this error linking a program with a 2 level dependence:
  g++ -o main -lcsparse sparseinterface.o main.cpp
the correct call is
  g++ -o main main.cpp sparseinterface.o -lcsparse 
But with gcc-4.0 both calls work perfectly.

1 comment:

  1. Ah, is that when gcc changed behaviour, between 4.0 and 4.4. Many of my previously compiling programs have been breaking because of this.