首页 > 解决方案 > 你如何构造一个 C makefile 以便它编译 source.c 文件?

问题描述

我有三个文件。main.c、graph.c 和 graph.h。我知道代码可以在没有 makefile 的情况下工作,因为我在 onlinegbd 编译器上对其进行了测试。一切运行顺利。

当我尝试在终端中运行我的 makefile 时,出现以下错误:

undefined reference to "function"

其中“函数”是我在 main 中调用的每个函数,它位于 graph.c 中。

所以这让我认为我没有在我的makefile中编译graph.c。

编辑 我已经确认它是makefile。我使用以下方法编译它:

gcc -o xGraph main.c graph.c

它运行没有问题。这是生成文件:

CC = gcc

VPATH = SRC INCLUDE

TARGET = XGraph

CFLAGS = -g -Wall

all: $(TARGET)

$(TARGET): main.o graph.o
    $(CC) main.o graph.o -o $(TARGET)

main.o: main.c graph.h
    $(CC) $(CFLAGS) main.c

graph.o: graph.c graph.h
    $(CC) $(CFLAGS) graph.c

clean:
    rm *.o *~ $(TARGET)

标签: cmakefile

解决方案


编译 C 代码时,第一阶段是生成.o文件。-c将标志传递给 gcc 以执行此操作。


main.o: main.c graph.h
    $(CC) $(CFLAGS) -c main.c

graph.o: graph.c graph.h
    $(CC) $(CFLAGS) -c graph.c

推荐阅读