gpt4 book ai didi

c - 在 C 中编译时如何修复 'undefined reference'?

转载 作者:太空宇宙 更新时间:2023-11-04 03:11:50 25 4
gpt4 key购买 nike

我正在尝试编译链接两个先前创建的目标文件的 C 程序,但不断收到“ undefined reference ”错误。

我使用 Visual Code 编写代码,使用 Windows 上的 Ubuntu 使用 makefile 进行编译。 task5.creverse.c 这两个 C 文件已被制成目标文件,它们都包含 #include reverse.h 语句,其中包含reverse.c 中函数的原型(prototype)。

task5.c

#include <stdio.h>
#include "ctap.h"
#include "reverse.h"

TESTS {
const char *a = "Family";
char *b = reverse(a);

//test 1
ok(string_length(a) == string_length(b), "Strings are the same size");

//test 2
is("ylimaF", b, "Strings match");
}

反向.c

#include <stdio.h>
#include <stdlib.h>
#include "reverse.h"

char *reverse(const char *str) {
//code
}

int string_length(const char *str) {
//code
}

反向.h

char *reverse(const char *str);
int string_length(const char *str);

生成文件

linked:
gcc -o linked task5.o reverse.o

task5.o
gcc -c -o task5.o task5.c

reverse.o
gcc -c -o reverse.o reverse.c

当我运行命令 make linked 时,我希望它被创建并且不返回任何内容。

但是当我运行该命令时出现此错误:

cc   task5.o   -o linked
task5.o: In function `ctap_tests':
task5.c:(.text+0x1abe): undefined reference to `reverse'
task5.c:(.text+0x1ace): undefined reference to `string_length'
task5.c:(.text+0x1adc): undefined reference to `string_length'
collect2: error: ld returned 1 exit status
<builtin>: recipe for target 'linked' failed
make: *** [task5] Error 1

最佳答案

根据 this GNU make documentation ,GNU make 程序将尝试使用 GNUMakefilemakefileMakefile

make 程序将不会尝试makefile.mk,这意味着例如make linked 将不使用 makefile,仅使用默认规则。

您可以通过将您的 makefile 重命名为 Makefile(最常见的)或 makefile 来解决这个问题;或者通过使用 -f 选项来指定 makefile

$ make -f makefile.mk linked

关于c - 在 C 中编译时如何修复 'undefined reference'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55605991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com