Link in the Math Library

Recently, I had question posed to from a reader from Norway. He was working his way through my book and found that one of the programs wouldn’t compile on his Linux computer. The problem was that the C language math library isn’t automatically linked. The effect is that a linker error appears upon compiling.

Weird thing: I get the same error on my Linux laptop. It was completely unexpected!

Here is sample code, which comes from a blog post on June 18, 2016:

#include <stdio.h>
#include <math.h>

int main()
{
    double t;

    for(t=1.0;t<=10.0;t++)
        printf("2 to the %.f power is %.f\n",
                t,
                pow(2.0,t));

    return(0);
}

I compiled at the command prompt using the following command:

clang -Wall 0618.c

The -Wall switch displays all errors, which is the default in Code::Blocks. Here’s the compiler output:

/tmp/0618-e49f59.o: In function 'main':
0618.c(.text+0x4d): undefined reference to `pow'
clang; error: linker command failed with exit code 1 (use -v to see invocation)

Ugh.

The clang program is both a compiler and linker. The source code is compiled into object code and, upon success, linked into a program file. Clang then removes the object code file, 0618.o in this example.

Back in the old days, two programs handled the process, cc and ld, the compiler and linker, respectively. Today, both clang and gcc (and cc) automatically call the ld program, the linker, to complete the task. That’s when the error happens because the pow() function lacks a definition — at least in the Linux computer’s standard C library.

On both the PC and the Mac, the math library is included in the standard C library — at least it appears so. Otherwise, the compiler automatically calls in the library. But in Linux, apparently, you must manually specify that the linker include the math library.

But isn’t the math library included with #include <math.h>

No!

If I comment out the #include directive, you get a compiler warning. Clang recommends that you include the math.h header file (which is one reason that I like and recommend that compiler), but you still see the linker error and the program doesn’t compile.

The solution is to use the -lx switch to direct clang to include the math library.

Libraries are typically stored in the /usr/lib folder in Unix, though the location can vary depending on the compiler. The math library goes by various names, but its abbreviation is m (lowercase M). To direct the linker to include the library, you must specify a linker switch when you compile:

clang -lm 0618.c

And the program finally compiles and links.

In next week’s Lesson I explore the process of adding a library in Code::Blocks, which is actually far more involved than using a command line switch, even if that’s what Code::Blocks does internally.

Leave a Reply