无法使用makefile链接math lib

var*_*wal 2 c gcc makefile

可能重复:
编译glib时链接器错误...?

好的,我知道这可能是重复的,但我找不到任何其他问题的答案.我正在尝试安装Pintos,当我在src/utils目录中运行'make'时,我得到的错误是对'floor'有一个未定义的引用.我检查了makefile,这是我得到的:

all: setitimer-helper squish-pty squish-unix
# 2207718881418

CC = gcc
CFLAGS = -Wall -W
LDFLAGS = -lm
setitimer-helper: setitimer-helper.o
squish-pty: squish-pty.o
squish-unix: squish-unix.o

clean: 
    rm -f *.o setitimer-helper squish-pty squish-unix
Run Code Online (Sandbox Code Playgroud)

我尝试添加LIBS = -lm,但这没有帮助.

make的输出:

gcc -lm  setitimer-helper.o   -o setitimer-helper
setitimer-helper.o: In function `main':
setitimer-helper.c:(.text+0xbb): undefined reference to `floor'
collect2: ld returned 1 exit status
make: *** [setitimer-helper] Error 1
Run Code Online (Sandbox Code Playgroud)

这种困境的任何解决方案?

Joh*_*all 5

您的原始makefile定义了一堆变量

CC = gcc
# etc
Run Code Online (Sandbox Code Playgroud)

并列出一些依赖项

setitimer-helper: setitimer-helper.o
# etc
Run Code Online (Sandbox Code Playgroud)

但除了clean规则之外,没有任何配方提供用于重新制作目标的确切命令.这意味着将使用内置的隐式规则; 例如,要setitimer-helper使用以下内置规则链接:

$(CC) $(LDFLAGS) $^ $(LDLIBS) -o $@
Run Code Online (Sandbox Code Playgroud)

对于setitemer-helper,使用相关依赖项填充自动变量:

$(CC) $(LDFLAGS) setitimer-helper.o $(LDLIBS) -o setitimer-helper
Run Code Online (Sandbox Code Playgroud)

从中你可以看到剩下的变量 - $(CC),$(LDFLAGS)$(LDLIBS)- 是如何填充的,以给出你看到的make的输出.

正如各种人所指出的那样,你需要确保链接命令-lm末尾,以便它可以用来满足对库函数的引用floor().此时,您的makefile设置$(LDFLAGS)-lm,但该变量在link命令的开头使用.

常规变量在此内置规则中设置,以便LDFLAGS可用于(历史上)需要位于链接命令开头的选项(也称为"标志"),并且LDLIBS可用于需要的库.在*.o目标文件之后指定.

因此,要根据您使用的makefile修复此问题,您需要-lmLDFLAGS已定义的变量中删除,而是为以下内容添加另一个变量定义LDLIBS:

LDLIBS = -lm
Run Code Online (Sandbox Code Playgroud)

(我稍微oversummarising:内置的规则还包含$(TARGET_ARCH)$(LOADLIBES),但那些不感兴趣的在这里.)