如何创建合适的 Makefile 以及依赖顺序是否重要?

How to create a proper Makefile and does the order of dependecies matter?

我有 5 个文件,我必须使用 makefile 来创建一个文件。

student.c has #include "student.h"

linkedlist.c has #include "linkedlist.h"

and main has #include "linkedlist.h" and #include "student.h"

student.c
student.h
linkedlist.c
linkedlist.h
main.c

我不知道顺序是否对解决依赖关系很重要。 我想我真正想问的是自下而上的依赖是什么意思??? 有人可以阐明如何在未来的项目中正确使用 makefile 吗?

基本上,你需要知道的是:

#You can make some const variables like `CC = gcc` 
#and use them in the Makefile like that `$(CC)` 
#(you basically wrap the variable with brackets and 
#put a dollar sign before it).

CC = gcc  

#The order is crutial in a makefile. 

# First of all you want to compile `main` using objects 
# which are yet to be linked.
main: student.o linkedlist.o
    # Line below is a command 
    # that is already well known to you I guess: "gcc -o main ..." 
    $(CC) -o main student.o linkedlist.o

# If makefile doesn't have the newest version of a .o file, 
# then it goes to lines below 
# to find out, how can it obtain the newest version 
# of student.o or linkedlist.o

# This is how it can produce the .o file:
student.o: student.c
    $(CC) -c student.c 
    # -c flag is crutial here, because it means that you want to create
    # a .o (object) file. Not an executable program.

# Same with linkedlist.c:
linkedlist.o: linkedlist.c
    $(CC) -c linkedlist.c

我希望它有效,我还没有测试过。如有错误请指正


还有一件事:记住你必须使用 TABS 而不是 SPACES 来缩进行。