簡體   English   中英

makefile 和多個.c 源文件的“未定義引用”

[英]“undefined reference to” with makefile and multiple .c source files

我正在嘗試使用 makefile 編譯和鏈接 4.c 文件和 ah 文件的項目。 我在鏈接階段遇到了一些問題,我似乎無法弄清楚問題是什么。 我已經包含了下面程序的主要結構,但沒有實際代碼(因為我對代碼本身沒有任何問題)。

The files are epsilon.c (the main project file), funcs.h which has the function declarations, and diffClock.c, equal.c and nameDigit.c which has function implementations. 這是家庭作業。

如果我先運行 make clean,一切似乎都正常,但如果我更新源代碼然后簡單地運行 make,或者從終端運行 -f makefile,則一切正常。 對於它的價值,我可以在沒有 makefile 的情況下從終端手動編譯和鏈接所有內容,所以我認為問題可能與 makefile 或我構建文件的方式有關。 任何幫助是極大的贊賞。

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...
}

等於.c:

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

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

名稱Digit.c:

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

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

函數.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 僅由主要的 function 組成:

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

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

和終端 output:

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

你不應該使用$? 在您的鏈接行中。

該變量擴展為通過調用 make 重建的 object 文件。 所以如果你只需要重建一個 object 文件,那么你只會鏈接一個 object 文件,這顯然是錯誤的。

您想改用$^ ,它會擴展到所有列為先決條件的 object 文件,無論它們是否被重建。

在 GNU 中制作$? 表示所有修改的先決條件。 您需要$^來滿足所有先決條件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM