【问题标题】:Why am I getting the error, "undefined reference to `pow' collect2: error: ld returned 1 exit status make: *** [p1] Error 1"?为什么我收到错误“未定义对‘pow’collect2的引用:错误:ld返回1退出状态make:*** [p1]错误1”?
【发布时间】:2017-01-30 03:22:58
【问题描述】:

这是我的生成文件:

CC=gcc 

CFLAGS=-g

LDFLAGS=-lm

EXECS= p1


all: $(EXECS)

clean: 
    rm -f *.o $(EXECS)

14:32:16 **** 构建项目 CH3-Programs 的默认配置 **** 使 p1 gcc -g -ggdb -lm p1.c -o p1 /tmp/ccNTyUSA.o:在函数main': /home/bm5788/fromVM/Workspace/CH3-Programs//p1.c:28: undefined reference topow' collect2:错误:ld 返回 1 个退出状态 制作:*** [p1] 错误 1 : 目标“p1”的配方失败

【问题讨论】:

  • makefile 将从哪些目标文件构建可执行文件p1?请发布运行make 命令的输出(在make clean 之后)。
  • 你在代码中使用 pow 函数吗?
  • 是的,我在代码中使用了 pow。
  • 我在哪里可以找到目标文件?
  • 我的意思是,你说all 依赖于$(EXECS)`(即p1)。但是$(EXECS) 依赖什么?

标签: c makefile math.h


【解决方案1】:

这里的问题是您与数学库链接的顺序(-lm 选项)。构建时,库应位于命令行中的源文件或目标文件之后。

所以如果你运行命令手动构建,它应该看起来像

gcc p1.c -o p1 -lm

问题在于您的makefile 并没有真正做任何事情,它仅依赖于隐式 规则。隐式规则以特定顺序使用某些变量,这些变量不会将库放在 makefile 中的正确位置。

试试像这样的makefile:

# The C compiler to use.
CC = gcc

# The C compiler flags to use.
# The -g flag is for adding debug information.
# The -Wall flag is to enable more warnings from the compiler
CFLAGS = -g -Wall

# The linker flags to use, none is okay.
LDFLAGS = 

# The libraries to link with.
LDLIBS = -lm

# Define the name of the executable you want to build.
EXEC = p1

# List the object files needed to create the executable above.
OBJECTS = p1.o

# Since this is the first rule, it's also the default rule to make
# when no target is specified. It depends only on the executable
# being built.
all: $(EXEC)

# This rule tells make that the executable being built depends on
# certain object files. This will link using $(LDFLAGS) and $(LDLIBS).
$(EXEC): $(OBJECTS)

# No rule needed for the object files. The implicit rules used
# make together with the variable defined above will make sure
# they are built with the expected flags.

# Target to clean up. Removes the executable and object files.
# This target is not really necessary but is common, and can be
# useful if special handling is needed or there are many targets
# to clean up.
clean:
    -rm -f *.o $(EXEC)

如果你使用上面的makefile运行makemake程序应该首先从源文件p1.c构建目标文件p1.o。然后是应该使用p1.o目标文件将可执行文件p1与标准数学库链接在一起。

【讨论】:

  • 是的!有效!非常感谢。真是太感谢你了。
  • @BryceMarshall 您可以通过投票和接受他的回答来更有效地感谢回答者:-)
猜你喜欢
  • 2020-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-06
  • 1970-01-01
  • 2013-06-01
  • 2014-09-03
相关资源
最近更新 更多