r/programmingquestions • • Mar 19 '24

Help understanding this Makefile?

Post image

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

2 comments sorted by

1

u/rsatrioadi May 23 '24

Let's break down the Makefile step by step.

  1. Variables:

    CC=gcc
    OBJ=obj
    REPOS=repository
    SRC=src
    TEMP=templates
    • CC: This is the compiler to be used, gcc in this case.

    • OBJ, REPOS, SRC, TEMP: These are variables holding directory names.

  2. Targets and Rules:

    .SECONDARY:
    • .SECONDARY: This is a special built-in target that marks all targets as secondary, meaning intermediate files won't be automatically deleted.

    ALL: hello
    • ALL: This is a custom target that depends on hello. It ensures hello is built when make is run.

  3. hello target:

    hello: $(OBJ)/hello.o
    	$(CC) -o hello $(OBJ)/hello.o
    	chmod u+x hello
    • hello: This target depends on $(OBJ)/hello.o.

    • $(CC) -o hello $(OBJ)/hello.o: This compiles the object file into the final executable hello.

    • chmod u+x hello: This changes the permissions to make the hello executable.

  4. Object file compilation:

    $(OBJ)/hello.o: $(SRC)/hello.c
    	$(CC) -I ./includes -c -o $(OBJ)/hello.o $(SRC)/hello.c
    • $(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 ./includes adds the includes directory to the list of directories to be searched for header files.

Summary

  • The make command will look for the ALL target first.

  • The ALL target depends on the hello target, which will compile the hello executable.

  • The hello target depends on the $(OBJ)/hello.o target, which will compile the hello.c file into hello.o.

  • After compiling the object file, it links it into the executable hello and makes it executable with chmod.