在makefile中未链接数学库的选项“-lm”。

9

我知道这个错误已经被反复讨论过了,但是我似乎无法让它正常工作。我在下面链接了我的makefile:

all: gensine info cs229towav

encode.o: encode.h encode.c
    gcc -c encode.c

write.o: write.c write.h
    gcc -c write.c

gensine.o: encode.c gensine.h gensine.c helper.c write.c
    gcc -c gensine.c -lm

helper.o: helper.c helper.h
    gcc -c helper.c

read.o: read.h read.c
    gcc -c read.c

info.o:read.c info.h info.c decode.c
    gcc -c info.c

decode.o: decode.c decode.h helper.c
    gcc -c decode.c

cs229towav.o: write.c read.c cs229towav.c cs229towav.h helper.c decode.c encode.c
    gcc -c cs229towav.c -lm

gensine: encode.o gensine.o write.o helper.o
    gcc -o gensine encode.o gensine.o write.o helper.o -lm

info: read.o info.o decode.o helper.o
    gcc read.o info.o decode.o helper.o

cs229towav: write.o read.o cs229towav.o decode.o encode.o helper.o
    gcc -o write.o read.o cs229towav.o decode.o encode.o helper.o -lm

Clean:
    rm -rf *o gensine info cs229towav

当我运行类似"make gensine"这样的命令时,会返回以下结果:
>cc gensine.c -o gensine
/tmp/ccojm09X.o: In function `encodeCsFormat':
gensine.c:(.text+0x4b1): undefined reference to `sin'
/tmp/ccojm09X.o: In function `encodeWavFormat':
gensine.c:(.text+0xa39): undefined reference to `sin'
collect2: error: ld returned 1 exit status

阅读后发现出现了对sin的未定义引用错误,这与math库有关。列出的这些函数在“encode.c”文件中,该文件被包含在“gensine.c”文件中。

3
这个输出片段似乎与上面的makefile不相符,你确定make正在使用正确的makefile吗? - fvu
1个回答

12

在Makefile中的命令:

gcc -o gensine encode.o gensine.o write.o helper.o -lm

与您在结尾处打印的命令不匹配:

cc gensine.c -o gensine

注意,这里没有-lm选项。

注意,make知道如何生成目标文件,所以你不需要大部分的makefile。尝试以下命令(记得用TAB进行缩进):

.PHONY : all clean
all = gensine info
CFLAGS =-Wall
LIBS = -lm

gensine: encode.o gensine.o write.o helper.o 
       gcc -o $@ $^ $(LIBS)

info: read.o info.o decode.o helper.o
       gcc -o $@ $^ $(LIBS)

cs229towav: write.o read.o cs229towav.o decode.o encode.o helper.o
       gcc -o $@ $^ $(LIBS)

clean:
       rm -rf *.o gensine info cs229towav

编辑:

Boddie,请注意你的困惑是因为你认为Makefile是一个脚本,也就是说当你输入make gensine时,你在运行名为make的脚本。实际上,make是一个命令,就像在文件系统中其他地方的gcc一样(在Linux等系统中,键入which make以查看它在哪里)。make命令期望在当前目录中找到一个名为makefileMakefile的构建规则输入文件。如果它没有找到该文件,则使用一些内置规则 - 因此,在你的Makefile中找不到的cc gensine.c -o gensine。如果您愿意,可以使用-f开关告诉make Makefile的名称(这样它就不会使用默认名称),就像@DanielFischer在评论中描述的那样。


我使用了该文件,但是我得到了与之前相同的错误。编译器的输出也是一样的。 - boddie
你叫什么名字的 makefile?目录中有多个 makefile 吗? - William Morris
我将其命名为“make”,没有扩展名,然后我调用了“make gensine”。 - boddie
哇塞!我没想到那个名字很重要。非常感谢你! - boddie
1
@boddie 或者称其为 make -f make gensine。如果您的 Makefile 文件名不是标准的,您必须告诉 make 使用哪个文件。在您的情况下,由于它没有找到标准名称之一,它使用了一个内置规则,糟糕。 - Daniel Fischer
make 识别特殊变量 LDLIBS。你可以使用它并指定 LDLIBS=-lm。这将使你不必使用 gcc -o $@ $^ $(LIBS) - loxaxs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接