Why do I get communication errors when calling a function in Math.h?

When I try to call functions in math.h , I get communication errors such as

 undefined reference to sqrt 

But I'm doing #include <math.h>
I use gcc and compile as follows:

 gcc -Wall -D_GNU_SOURCE blah.c -o blah 

Why can't the linker find a definition for sqrt ?

+4
source share
3 answers

Add -lm to the command when calling gcc:
gcc -Wall -D_GNU_SOURCE blah.c -o blah -lm

This will allow the linker to link to the math library. Including math.h will tell the compiler that mathematical functions such as sqrt () exist, but they are defined in a separate library, which the linker must pack with your executable.

As FreeMemory notes, the library is called libm.a. On Unix-like systems, the rule for naming libraries is lib [blah] .a. Then, if you want to link them to your executable, you use -l [blah].

+7
source

You need to link the math library explicitly. Add -lm to the flags you pass to gcc so that the linker knows to link libm.a

+2
source

Add -lm to the end of the gcc command to link the math library:

 gcc -Wall -D_GNU_SOURCE blah.c -o blah -lm 

For proper binding of things, the order of the compiler flags matters! In particular, -lm should be placed at the end of the line .

If you're wondering why the math.h library should be enabled at all when compiling in C, check out this explanation here .

0
source

Source: https://habr.com/ru/post/1276939/


All Articles