如何创建一个合适的Makefile并确定dependecies的顺序?

时间:2015-05-03 23:51:38

标签: c makefile

我有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用于未来的项目吗?

1 个答案:

答案 0 :(得分:1)

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

#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来缩进行。