Linking with gcc and -lm doesn’t define ceil() on Ubuntu

Take this code and put it in a file ceil.c:

#include <math.h>
#include <stdio.h>
int main(void)
{
    printf("%f\n", ceil(1.2));
    return 0;
}

Compile it with:

$ gcc -o ceil ceil.c
$ gcc -o ceil ceil.c -lm

One of those two should work. If neither works, show the complete error message for each compilation. Note that -lm appears after the name of the source file (or the object file if you compile the source to object before linking).

Notes:

  1. A modern compiler might well optimize the code to pass 2.0 directly to printf() without calling ceil() at all at runtime, so there’d be no need for the maths library at all.

  2. Rule of Thumb: list object files and source files on the command line before the libraries. This answer shows that in use: the -lm comes after the source file ceil.c. If you’re building with make etc, then you typically use ceil.o on the command line (along with other object files); normally, you should list all the object files before any of the libraries.

There are occasionally exceptions to the rule of thumb, but they are rare and would be documented for the particular cases where the exception is expected/required. In the absence of explicit documentation to the contrary, apply the rule of thumb.

Leave a Comment