r/programmingquestions • u/ThiccOrc • Mar 19 '24
Help understanding this Makefile?
Hello, I am taking a programming class that goes over many different paradigms. It is my first exposure to Linux and despite reading the book and going over class videos I am helplessly lost. I was able to make the programs run but my professor also wants us to make comments in the Makefile and I have been lost trying to understand how the file works. Any insight would be much appreciated.
3
Upvotes
1
u/rsatrioadi May 23 '24
Let's break down the Makefile step by step.
Variables:
CC: This is the compiler to be used,gccin this case.OBJ,REPOS,SRC,TEMP: These are variables holding directory names.Targets and Rules:
.SECONDARY: This is a special built-in target that marks all targets as secondary, meaning intermediate files won't be automatically deleted.ALL: This is a custom target that depends onhello. It ensureshellois built whenmakeis run.hello target:
hello: This target depends on$(OBJ)/hello.o.$(CC) -o hello $(OBJ)/hello.o: This compiles the object file into the final executablehello.chmod u+x hello: This changes the permissions to make thehelloexecutable.Object file compilation:
$(OBJ)/hello.o: This target depends on$(SRC)/hello.c.$(CC) -I ./includes -c -o $(OBJ)/hello.o $(SRC)/hello.c: This compiles the C source file into an object file.-I ./includesadds theincludesdirectory to the list of directories to be searched for header files.Summary
The
makecommand will look for theALLtarget first.The
ALLtarget depends on thehellotarget, which will compile thehelloexecutable.The
hellotarget depends on the$(OBJ)/hello.otarget, which will compile thehello.cfile intohello.o.After compiling the object file, it links it into the executable
helloand makes it executable withchmod.