21

What does -lm option do in g++ and when is it needed?

Is there a complete description of g++ options?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
a-z
  • 1,634
  • 4
  • 16
  • 35
  • 1
    There's a complete list in GCC's documentation (man gcc). – Mat May 04 '12 at 11:21
  • Duplicate of [sqrt from math.h causes compile error](http://stackoverflow.com/questions/1711915/sqrt-from-math-h-causes-compile-error). Also related to [gcc: why the -lm flag is needed to link the math library?](http://stackoverflow.com/questions/4606301/gcc-why-the-lm-flag-is-needed-to-link-the-math-library) – Abhijit May 04 '12 at 11:21
  • possible duplicate of [Why I'm Getting "undefined reference to `sqrt' " Error, Even Though I include math.h header?](http://stackoverflow.com/questions/10409032/why-im-getting-undefined-reference-to-sqrt-error-even-though-i-include-ma) – Alexey Frunze May 04 '12 at 11:24
  • 1
    Why does my g++ compile without it?(at least this part is not duplicate) – a-z May 04 '12 at 11:31

2 Answers2

28

That's a linker option. It tells the linker to link with (-l) the m library (libm.so/dll). That's the math library. You often need it if you #include <math.h>.

Mat
  • 202,337
  • 40
  • 393
  • 406
13

The option does nothing for g++: referring to this answer https://stackoverflow.com/a/1033940/1143274 libstdc++ requires libm, so it will always be linked by g++.

However, there is also some sort of an automatic linking behaviour for gcc, investigated on this thread http://www.linuxforums.org/forum/programming-scripting/125526-c-gcc-math-h-lm.html which I can't seem to find an answer as to where that comes from and which libraries it applies to...

Community
  • 1
  • 1
Evgeni Sergeev
  • 22,495
  • 17
  • 107
  • 124