c - C 新手,使用包含的 header 中声明的方法时出现链接错误

标签 c linker ld

我是 c 语言新手,我正在尝试在 main.c 类中使用 tester 中的方法。

这是 main.c:

#include <stdbool.h>
#include <stdio.h>

#include "tester.h"

int main(void) {
    bool is_valid = isTrue();
}

这是 tester.h:

#include <stdbool.h>

bool isTrue();

这是 tester.c:

#include "tester.h"

bool isTrue() {
    return true;
    }

这是我尝试编译时发生的情况:

$ make main tester
gcc -g -O0 -Wall --std=c99 -pedantic  -g -O0  main.c   -o main
main.c: In function ‘main’:
main.c:7:10: warning: unused variable ‘is_valid’ [-Wunused-variable]
     bool is_valid = isTrue();
          ^
/tmp/ccwIzgJQ.o: In function `main':
/home/paul/CS261/p1-check/mess/main.c:7: undefined reference to `isTrue'
collect2: error: ld returned 1 exit status
make: *** [main] Error 1

我的 Makefile 是由我的教授提供的。我可以在这里发布内容,但我确信它是正确的。我知道这里发生了链接错误,但为什么呢?我在 main.c 中包含了 tester.h 文件,所以不应该定义 isTrue 吗?我们将非常感谢您的帮助。

编辑:这是 Makefile:

# Simple Makefile
# 
#
# This makefile builds a simple application that contains a main module
# (specified by the EXE variable) and a predefined list of additional modules
# (specified by the MODS variable). If there are any external library
# dependencies (e.g., the math library, "-lm"), list them in the LIBS variable.
# If there are any precompiled object files, list them in the OBJS variable.
#
# By default, this makefile will build the project with debugging symbols and
# without optimization. To change this, edit or remove the "-g" and "-O0"
# options in CFLAGS and LDFLAGS accordingly.
#
# By default, this makefile build the application using the GNU C compiler,
# adhering to the C99 standard with all warnings enabled.


# application-specific settings and run target

EXE=y86
MODS=p1-check.o
OBJS=
LIBS=

default: $(EXE)

test: $(EXE)
    make -C tests test

# compiler/linker settings

CC=gcc
CFLAGS=-g -O0 -Wall --std=c99 -pedantic
LDFLAGS=-g -O0


# build targets

$(EXE): main.o $(MODS) $(OBJS)
    $(CC) $(LDFLAGS) -o $(EXE) $^ $(LIBS)

%.o: %.c
    $(CC) -c $(CFLAGS) $<

clean:
    rm -f $(EXE) main.o $(MODS)
    make -C tests clean

.PHONY: default clean

当我尝试使用 Makefile 进行链接时,我是否缺少命令的一部分?这可能是我的问题,但我不确定是什么。

最佳答案

我发现我做错了什么。当我想用 make main.o 链接文件时,我应该说 make main.o 。看来我没有对 Makefile 中的构建命令给予足够的关注。感谢 kaylum 对声明和定义之间的澄清。

关于c - C 新手,使用包含的 header 中声明的方法时出现链接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39540242/

相关文章:

c - 如何使用 chdir() 函数返回目录?

c++ - C++ 中的编译和链接

c++ - 找不到 sin(double)、sin(double&)、cos(double)、cos(double&)

linux - 将 uclibc 链接器用于 glibc 编译的二进制文件?

c - OpenGL正弦函数向点移动

c - 具有相同名称的宏和函数

javascript - selenium 使用 javascript 定位没有 id 或 name 的元素

xcode - 当我将一个项目拖放到另一个项目的树中时,XCode 5.1崩溃

android - 检查需要哪些库

c - 当 dlopen one 时,它​​的符号没有被主符号覆盖,为什么?