简体   繁体   English

Makefile:“对cos的未定义引用”

[英]Makefile: “undefined reference to cos”

I have just started learning about makefile files. 我刚刚开始学习makefile文件。 I created a program that consists of two functions and wanted to use a makefile to put it all together. 我创建了一个由两个函数组成的程序,并希望使用一个makefile将它们放在一起。 This is my file: 这是我的文件:

#Makefile

all: main

main: main.o find_root.o
    clang -o main main.o find_root.o

main.o: main.c
    clang -c -Wall --pedantic -std=c11 main.c -lm

find_root.o: find_root.c
    clang -c -Wall --pedantic -std=c11 find_root.c -lm

clean: rm -f main *.o*

However, when I run this, I get an error - "undefined reference to cos". 但是,当我运行此命令时,出现错误-“未定义对cos的引用”。 I am using the cosine functions in my program, but I have already linked the library to the compilation of those two files. 我在程序中使用余弦函数,但是已经将库链接到这两个文件的编译中。 I thought about adding "-lm" to the first clang option as well. 我还考虑过将“ -lm”添加到第一个clang选项中。 This led to no errors, but it made a warning instead - saying that "-lm linker is unused". 这没有导致任何错误,但是发出了警告-表示“ -lm链接器未使用”。 What should I change in my file? 我应该在文件中更改什么?

The "-lm" is a linker option but you have only included it in your compilation rule ( main.o: main.c ). “ -lm”是一个链接器选项,但您仅将其包括在编译规则中( main.o: main.c )。 You need to include it in your linker rule ( main: main.o find_root.o ). 您需要将其包括在链接器规则中( main: main.o find_root.o )。

As it stand the -lm option is ignored during compilation and missing during linking. 就目前而言, -lm选项在编译期间会被忽略,而在链接期间会丢失。

The linker flags aren't used when compiling, but when linking, so the command for the main rule should have -lm , rather than the command for the *.o files. 链接器标志在编译时不使用,而是在链接时使用,因此main规则的命令应具有-lm ,而不是*.o文件的命令。

Better would be just to set the appropriate variables, and let Make use its built-in rules: 最好是设置适当的变量,并让Make使用其内置规则:

#Makefile

LDLIBS += -lm
CFLAGS += -Wall --pedantic -std=c11
C = clang

all: main

main: main.o find_root.o
    $(LINK.c) $^ $(LDLIBS) -o $@

clean:
    $(RM) main *.o *~

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM