Undefined reference to 'pow' even though -lm is a compile flag. [C]

让人想犯罪 __ 提交于 2019-12-28 23:48:05

问题


Any reason

cc -g -lm -DBLITZ_HOST_IS_LITTLE_ENDIAN

would produce an error with code using math.h? Is it possible there's a difference between GCC version 4.0.3 (documented working version) and version 4.6.3 (my current version)?

makefile and asm.c @ https://gist.github.com/3801291

This is on ubuntu 12.04

My terminal output is a comment in the gist.


回答1:


Instead of

cc -g -lm -DBLITZ_HOST_IS_LITTLE_ENDIAN foo.c

Try:

cc -g -DBLITZ_HOST_IS_LITTLE_ENDIAN foo.c -lm

When the linker searches a library, it links in modules that contain definitions for previously-undefined symbols.

If the linker searches -lm before foo.o, then pow() is not yet undefined. Conversely, if foo.o comes first, it undefines pow(), which -lm can then resolve.


EDIT: To accomplish this advice in your makefile, make these changes:

CFLAGS=-g -DBLITZ_HOST_IS_LITTLE_ENDIAN
LDLIBS=-lm

...

asm: asm.c
        $(CC) $(CFLAGS) asm.c $(LDLIBS) -o asm



回答2:


I've recently suffer this problem using an automatic builder, namely drone.io.

The problem was that gcc in Ubuntu 12.04 was linking by default with -Wl,--as-needed. In my case, the project was using autotools, which means I was too lazy to write anything to modify the compilation order. Instead, modifying as-needed flag fixed the problem.

-gabriel_LDFLAGS = $(GLIB2_LIBS) $(DBUS_LIBS) -lssh
+gabriel_LDFLAGS = -Wl,--no-as-needed $(GLIB2_LIBS) $(DBUS_LIBS) -lssh

For full info, you can check the fixing commit in https://bitbucket.org/kikeenrique/gabriel/commits/f08eefdca3f7bb90f48f5a6fbfc8839422572508

You can take a look to the log with errors BEFORE applying the fix and also you can take a look to the log without errors AFTER applying the fix.



来源:https://stackoverflow.com/questions/12644922/undefined-reference-to-pow-even-though-lm-is-a-compile-flag-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!