0

I am a rookie to MaKefile and I've been learning it recently. However, I got trouble when I tried to run make command on my terminal. Here's my Makefile:

CC = g++
CFLAGS = -g -Wall
bin = ./bin/

makedir:
        @echo "build ./bin"
        mkdir  $(bin)

all: algo

OBJS = $(patsubst %.o, $(bin)%.o, BB.o BF.o method.o algo.o)

algo: BB.o BF.o method.o algo.o
        $(CC) -o algo $(OBJS)

BB.o: BB.cpp 
        $(CC) $(CFLAGS) -c $^ -o $(bin)$@
BF.o: BF.cpp 
        $(CC) $(CFLAGS) -c $^ -o $(bin)$@
method.o: method.cpp
        $(CC) $(CFLAGS) -c method.cpp -o $(bin)$@
algo.o: algo.cpp method.hpp
        $(CC) $(CFLAGS) -c algo.cpp -o $(bin)$@

clean:
        -rm -f $(bin)*
        -rmdir $(bin)
        -rm -f algo

I tried to put object files in bin directory. But, the terminal only shows:

build ./bin
mkdir bin

And here's the problem. Only a empty directory named bin being created. It seems like it didn't do anything after mkdir command.

For more details, it's my directory structure before running make command:

├── algo.cpp
├── BB.cpp
├── BF.cpp
├── Makefile
├── method.cpp
├── method.hpp

I have no idea about it at all, and tried to find any way to solve it but useless. By the way, I am also a rookie to Stackoverflow. If I don't ask questions at a good way, let me know and I will get better. Thank you so much!

scorer hsu
  • 13
  • 3

1 Answers1

1

When you run make without arguments, the recipe for the first target in the Makefile is followed.

Your first target is makedir, whose recipe performs those two commands and nothing else. So, the computer is doing what you asked it to do.

I recommend that you put the all target first, and make makedir a prerequisite of the targets that actually do rely on it:

CC = g++
CFLAGS = -g -Wall
bin = ./bin/

all: algo

OBJS = $(patsubst %.o, $(bin)%.o, BB.o BF.o method.o algo.o)

algo: BB.o BF.o method.o algo.o
        $(CC) -o algo $(OBJS)

BB.o: makedir BB.cpp 
        $(CC) $(CFLAGS) -c $^ -o $(bin)$@
BF.o: makedir BF.cpp 
        $(CC) $(CFLAGS) -c $^ -o $(bin)$@
method.o: makedir method.cpp
        $(CC) $(CFLAGS) -c method.cpp -o $(bin)$@
algo.o: makedir algo.cpp method.hpp
        $(CC) $(CFLAGS) -c algo.cpp -o $(bin)$@

makedir:
        @echo "build ./bin"
        mkdir  $(bin)

clean:
        -rm -f $(bin)*
        -rmdir $(bin)
        -rm -f algo

There are better ways to handle build output directory creation, though (example).

Asteroids With Wings
  • 17,071
  • 2
  • 21
  • 35