C Failing to compile: Can’t find math.h functions [duplicate]

-lm needs to added to the command line after the file that requires that library for example if main.c required the math library then you would use:

 gcc -x c main.c -lm 

You can see a live example here, there are three command lines available in the example. One without -lm, one with -lm before the file that needs it one after the files that needs it.

For completeness sake if we refer to the gcc docs on options for Linking it says the following for -l:

[…]It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, ‘foo.o -lz bar.o’ searches library ‘z’ after file foo.o but before bar.o. If bar.o refers to functions in ‘z’, those functions may not be loaded. […]

Leave a Comment