NotSure
NotSure

Reputation: 69

Makefile for starters (C++)

I'm working on a small C++ project composed by different folders in the following way

Project
|
|-src (several .cpp files here - that depend on their .hpp)
|-include (several .hpp files here)
|-test(various things, not really important)
|-bin
|-build

What I'd like to do is to be able to put my object files (.o) into the "build" folder and I want to make sure my Output.exe gets into "bin". This way, when I "make clean" I can simply "remove *.o from build" and "remove Output.exe from bin".

I've read some solutions but it doesn't look like I can make it work in any way. Can someone help me out on this? Thanks

Right now I've come up with something like this:

CC = c++

INC_DIR = ./include
SRC_DIR = ./src
BUILD_DIR = ./build

CPPFLAGS = -Wall -Wfatal-errors -std=c++11

SRCS = $(shell find $(SRC_DIR) -name *.cpp)
DEPS = $(shell find $(IND_DIR) -name *.hpp)
OBJS = $(SRCS:%=$(BUILD_DIR)/%.o)

INC_FLAGS = -I $(INC_DIR) -I $(SRC_DIR)
CPPFLAGS = -Wall -Wfatal-errors -std=c++11
FLAGS = $(INC_FLAGS) $(CPPFLAGS)

$(BUILD_DIR)/%.o : %.cpp $(DEPS)
    $(CC) -c -o $@ $< $(FLAGS)

.PHONY: clean

clean:
    rm -rf $(BUILD_DIR)/*.o

When I type "make" it says - rm -rf $(BUILD_DIR)/*.o which means he's trying to clean. Problem is that it didn't even try to compile

Upvotes: 1

Views: 104

Answers (1)

Klaas van Gend
Klaas van Gend

Reputation: 1128

You're missing your final make target, bin/test.exe. Personally, I don't like $(shell) much - see my solution below.

SRC       := $(wildcard src/*.cpp)
OBJ       := $(patsubst src/%.cpp,build/%.o,$(SRC))

vpath %.cpp src

CC        := g++
LD        := g++

build/%.o: %.cpp
    $(CC) -Iinclude -c $< -o $@

.PHONY: all clean

all: build bin bin/test.exe

bin/test.exe: $(OBJ)
    $(LD) $^ -o $@

clean:
    @rm -rf build/* bin/*

Upvotes: 2

Related Questions