Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c math linker problems on Ubuntu 11.10 [duplicate]

Some strange error appeared after I upgraded my Ubuntu from (10.11, 11.04 i dont know) to 11.10.

I am getting an undefined reference to 'sqrt' while using math.h and linking with -lm

I'm compiling with gcc -Wall -Werror -g -Iinclude/ -lm lib/matrix.c src/analyse.c -o bin/analyse.o both source-files use and include math.h.

This code compiled without problems for and I didn't change much since the upgrade but now it won't work.

Do you have any suggestions what I can do, to find the error?

I'm sorry, if this question was asked before; there are so many posts on math linker errors and I didn't find a matching one

like image 964
Hachi Avatar asked Oct 19 '11 16:10

Hachi


3 Answers

The library that you are using needs to be placed after the files that use it when you are using it from the command line. So place -lm on after your C files on the command line.

Reference

like image 172
user786653 Avatar answered Nov 06 '22 10:11

user786653


SOLVED, this is not the common missing -lm problem! I'm in the same situation after upgrade to (k)ubuntu 11.10!

$ whereis math.h
math: /usr/include/math.h

Makefile:
CC=gcc
CFLAGS=--std=c99 -g -pedantic -Wall -lm

uname:
Linux idefix 3.0.0-12-generic #20-Ubuntu SMP Fri Oct 7 14:56:25 UTC 2011 x86_64 x86_64 x86_64 GNU/Linux

You really HAVE TO place the -lm swith after -o foo foo.c parameter

Output:
pidi@idefix:~/projekt1$ make
gcc -o b1 b1.c --std=c99 -g -pedantic -Wall -lm
pidi@idefix:~/projekt1$

So swap your flags in Makefile! GUYS. This is pretty new (and serious) BUG!

like image 17
quido.speedy Avatar answered Nov 06 '22 11:11

quido.speedy


This is a problem due to the default activation of the gcc flag --as-needed in the linker

More information here: http://www.gentoo.org/proj/en/qa/asneeded.xml

Simple fix (worked for me at least):

Add -Wl,--no-as-needed to the linker

like image 10
Seldon_SL Avatar answered Nov 06 '22 12:11

Seldon_SL