C makefile undefined reference 错误

标签 c makefile undefined-reference

我在 C 中使用 makefile 时遇到了一些小问题。我一直在遵循教科书中的教程,但它似乎不想工作。我有三个文件,message_hider.c、encrypt.h 和 encrypt.c。当我为这些文件创建 makefile 时,它​​会返回错误,但是当我单独运行每个命令时,它工作得很好。这是我的文件。

加密.c

#include "encrypt.h"

void encrypt(char *message) {
char c;
while (*message) {
*message = *message ^ 31;
message++;
}
}

message_hider.c

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

int main() {
char msg[80];
while (fgets(msg, 80, stdin)) {
encrypt(msg);
printf("%s", msg);
}
}

加密.h

void encrypt(char *message);

生成文件

message_hider: message_hider.o encrypt.o
    gcc message_hider.o encrypt.o -o message_hider
message_hider.o: message_hider.c encrypt.h
    gcc -c message_hider.c
encrypt.o: encrypt.c encrypt.h
    gcc -c encrypt.c

错误信息

$ make message_hider
cc   message_hider.o   -o message_hider
message_hider.o:message_hider.c:(.text+0x17): undefined reference to `encrypt'
message_hider.o:message_hider.c:(.text+0x17): relocation truncated to fit: R_X86_64_PC32       against undefined symbol `encrypt'
/usr/lib/gcc/x86_64-pc-cygwin/4.8.2/../../../../x86_64-pc-cygwin/bin/ld:     message_hider.o: bad reloc address 0x0 in section `.pdata'
/usr/lib/gcc/x86_64-pc-cygwin/4.8.2/../../../../x86_64-pc-cygwin/bin/ld: final link    failed: Invalid operation
collect2: error: ld returned 1 exit status
<builtin>: recipe for target 'message_hider' failed
make: *** [message_hider] Error 1

最佳答案

$ make message_hider
cc   message_hider.o   -o message_hider

不是您在 makefile 中指定的规则。首先,它似乎使用的是 cc 而不是 gcc。其次,其中没有提及encrypt.o,这就是您的链接失败的原因。

尝试显式使用 makefile,例如:

make -f Makefile message_hider

它可能会选择不同的 makefile,该文件要么具有不同的规则,要么仅依赖于默认规则,例如 .c.o

<小时/>

并且,根据您的更新:

make -f Makefile message_hider

给你:

$ make -f Makefile message_hider
make: Makefile: No such file or directory
make: *** No rule to make target 'Makefile'. Stop.

这是当 Makefile 实际上不存在时出现的错误。

因此您需要检查它是否位于当前目录中,并且名称是否与您期望的完全一致。

这可以解释前面提到的默认规则的使用,因为您的 makefile 实际上并未被选取。

另一件需要检查的事情是,您实际上正在运行正确的 make 程序,尽管现在我们已经看到了上面的错误,这可能没有实际意义。使用 which make 找出它的位置(在 CygWin 上应为 /usr/bin/make)并使用 make --version 检查版本。

关于C makefile undefined reference 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22030466/

相关文章:

shell - 如何在makefile函数中传递逗号字符

c++ - 重用相同的规则来构建不同的目标

c++ - 我可以在 makefile 中使用其他名称来表示 CC、CFLAGS 还是将它们硬连接到 GNU make 中?

c++ - 什么是 undefined reference /未解析的外部符号错误以及如何修复它?

c++ - "undefined reference to"当我试图继承 vector 类时

c - 二维数组的 malloc()

c - 具有多个数据字段的通用列表 C

c - 如何在 Cmake 中链接 curses.h?

c - 每次调试时变量的地址都会改变吗

c - 在运行时模拟命令行参数