"undefined reference to" 带有 makefile 和多个 .c 源文件

"undefined reference to" with makefile and multiple .c source files

我正在尝试使用 makefile 编译和 link 一个包含 4 个 .c 文件和一个 .h 文件的项目。我在 linking 阶段遇到了一些问题,我似乎无法弄清楚问题是什么。我在下面包含了程序的主要结构,但没有实际代码(因为我对代码本身没有任何问题)。

这些文件是 epsilon.c(主项目文件),funcs.h 具有函数声明,以及 diffClock.c、equal.c 和 nameDigit.c有函数实现。这是作业。

如果我先 运行 make clean 似乎一切正常,但如果我更新源代码然后简单地从终端 运行 make 或 make -f makefile 就不行了。对于它的价值,我可以在没有 makefile 的情况下从终端手动编译和 link 所有内容,所以我认为问题可能出在 makefile 或我构建文件的方式上。非常感谢任何帮助。

生成文件如下所示:

CFLAGS   =  -fwrapv # This is a macro definition
LDFLAGS  =  -lm

OBJECTS =  epsilon.o diffClock.o equal.o nameDigit.o funcs.h

default : out.txt
    cat out.txt

out.txt : epsilon                 
    ./$< > $@      

epsilon : $(OBJECTS) # epsilon depends on epsilon.o
    $(CC) $? -o $@ $(LDFLAGS)                   

.PHONEY: clean
clean:                         
    rm -f out.txt epsilon $(OBJECTS) 

diffClock.c:

#include <time.h>
#include "funcs.h"

double diffClock(clock_t clock1, clock_t clock2)
{
    // some code...
}

equal.c:

#include "funcs.h"
#include <math.h>

int equal(double a, double b, double tau, double epsilon){
// some code...
}

nameDigit.c:

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

void name_digit( int dig ){
// some code...
}

funcs.h:

#ifndef EPSILON_FUNCS_H
#define EPSILON_FUNCS_H
#include <time.h>

extern double diffClock(clock_t clock1, clock_t clock2);

extern int equal(double a, double b, double tau, double epsilon);

extern void name_digit( int dig );

#endif //EPSILON_FUNCS_H

最后epsilon.c只是主要功能组成:

#include <math.h>
#include <stdio.h>
#include <assert.h>
#include <limits.h>
#include <float.h>
#include "funcs.h"

int main(){
  // some code...
  return 0;
}

终端输出:

make
gcc -fwrapv    -c -o epsilon.o epsilon.c
gcc epsilon.o -o epsilon -lm                    # Now we link the object file to an output program ('-o') called epsilon.
/usr/bin/ld: epsilon.o: in function `main':
epsilon.c:(.text+0x90): undefined reference to `diffClock'
/usr/bin/ld: epsilon.c:(.text+0xd8): undefined reference to `diffClock'
/usr/bin/ld: epsilon.c:(.text+0x11e): undefined reference to `diffClock'
/usr/bin/ld: epsilon.c:(.text+0x1dd): undefined reference to `diffClock'
/usr/bin/ld: epsilon.c:(.text+0x225): undefined reference to `diffClock'
/usr/bin/ld: epsilon.o:epsilon.c:(.text+0x26b): more undefined references to `diffClock' follow
/usr/bin/ld: epsilon.o: in function `main':
epsilon.c:(.text+0x8b7): undefined reference to `name_digit'
collect2: error: ld returned 1 exit status
make: *** [makefile:37: epsilon] Error 1

您不应在 link 行中使用 $?

该变量扩展为通过调用 make 重建的目标文件。所以如果你只需要重建一个目标文件,那么你只会link一个目标文件,这显然是错误的。

您想改用 $^,这会扩展到 所有 作为先决条件列出的目标文件,无论它们是否重建。

在 GNU 中 make $? 表示所有已修改的先决条件。您需要 $^ 满足所有先决条件。