c - 使用 makefile 时 undefined reference

标签 c makefile header-files

我有一个给定的 makefile,由我们的教授编写。 `

SHELL  = /bin/bash
CC     = gcc
CFLAGS = -Wall -W -std=c99 -pedantic
LIBS   =

# Rajouter le nom des executables apres '=', separes par un espace.
# Si une ligne est pleine, rajouter '\' en fin de ligne et passer a la suivante.

# To compile without bor-util.c file 
EXECS = main

# To compile with bor-util.c file 
EXECSUTIL = 

# To compile with bor-util.c & bor-timer.c files
EXECSTIMER = 


.c.o :
    $(CC) -c $(CFLAGS) $*.c

help ::
    @echo "Options du make : help all clean distclean"

all :: $(EXECS) $(EXECSUTIL) $(EXECSTIMER)

$(EXECS) : %: %.o 
    $(CC) -o $@ $@.o $(LIBS)

$(EXECSUTIL) : %: %.o bor-util.o
    $(CC) -o $@ $@.o bor-util.o $(LIBS)

$(EXECSTIMER) : %: %.o bor-util.o bor-timer.o
    $(CC) -o $@ $@.o bor-util.o bor-timer.o $(LIBS)

clean ::
    \rm -f *.o core

distclean :: clean
    \rm -f *% $(EXECS) $(EXECSUTIL) $(EXECSTIMER)
`

我们在这个项目中所要做的就是将我们的代码写在其他文件中,然后像往常一样使用这个 makefile 进行编译。 我写了一个 helloWorld 函数来测试。我有3个文件 函数.C

#include <stdio.h>
#include "functions.h"


    void printMsg(){
        printf("Hello World !");
    }

函数.H

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

void printMsg();
#endif /* FUNCTIONS_H */

还有一个 MAIN.C 文件来测试所有内容

#include "functions.h"


int main(){

    printMsg(); 
    return 0;
}

并且我已经将 main 添加到 makefile 中。但是我在编译的时候得到这个错误信息

gcc -o main main.o 
main.o: In function `main':
main.c:(.text+0xa): undefined reference to `printMsg'
collect2: error: ld returned 1 exit status
Makefile:32: recipe for target 'main' failed
make: *** [main] Error 1

有谁知道解决方案是什么?谢谢

最佳答案

错误信息很明确:链接器没有找到printMsg函数。这是完全正常的:执行的链接命令是:

gcc -o main main.o

看到了吗?没有 functions.o 的痕迹,其中实现了 printMsg 函数。要解决此问题,您必须使用此命令链接:

gcc -o main main.o functions.o

问题是你的 Makefile 没有提到 functions.o 作为 main 的先决条件,它也没有在配方中使用它。要么你没看懂教授的说明(他没有让你添加functions.cfunctions.h),要么你忘了他还说明了如何更新Makefile,或者他的Makefile不兼容他自己的指令。在后两种情况下,您可以通过更改 $(EXECS) 的规则来调整 Makefile:

$(EXECS) : %: %.o functions.o
    $(CC) -o $@ $^ $(LIBS)

$^ 扩展为所有先决条件的列表,即在您的情况下,main.o functions.o。这条新规则将:

  1. 如果 main.ofunctions.o 发生变化,则重新构建 main
  2. 链接 main.o functions.o

警告:如果您在 $(EXECS) 中列出了不依赖于 functions.o 或依赖于其他目标文件的其他可执行文件,或者如果您如果有更多其他文件,如 functions.o,您将需要一些更复杂的东西。问一个新问题。

注意:由于 SO 是英文,所以最好翻译示例代码中的法文注释。我建议:

Add the executable names after '=', separated by one space. If a line is full, add a '\' at the end and continue on the next line.

最后一点:字母大小写很重要。如果您的文件是 functions.c,请不要在您的问题中键入 FUNCTIONS.C。与其他文件名相同。

关于c - 使用 makefile 时 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46416811/

相关文章:

c++ - 我什么时候需要使用/拥有 makefile?

C:查找字符串中的特定字符

makefile - 如何让 CMake 使用现有的 Makefile?

python - 如何在 Python 包中包含共享 C 库

makefile - make - 模式规则目标被错误地视为中间对象

c - 如何在没有 eof 的情况下 recv 直到没有更多的 recv?

C字面后缀U、UL问题

c - 在 C 编程中,如何将两个头文件和 3 个 c 文件链接到一个可执行文件中?

c++ - 在不使用 C++11 的情况下在头文件中初始化数组的替代方法

c++ - 防止 CMake 为仅可选 header 库生成的 makefile 在仅 header 模式下编译源文件