Search code examples
c++makefileg++windows-subsystem-for-linux

How do I create object files into a different directory than Makefile's one?


I'm new on using Makefiles because I've been programming with VS2019 on Windows, solving all my compilation and linking problems.

This is the result:

BUILD_DIR:= ./build
SRC_DIRS := ./src
INCL_DIR := ./includes
CC := /usr/bin/g++      #Compiler used
LVERSION := -std=c++17  #Language Version
CXXFLAGS := -g          #Cpp flags
CFLAGS := -Wall         #Compiler Flags
LFLAGS := -lstdc++fs    #Linker Flags
SRCS := Audio.cpp Song.cpp Visual.cpp VisualSong.cpp
LIBS := 
INCLUDES := $(SRCS:%.cpp=$(INCL_DIR)/%.h)
OBJS := $(SRCS:%.cpp=$(BUILD_DIR)/%.o)
PROG := progName.exe

progName: $(OBJS)
    $(CC) $(CFLAGS) $(CXXFLAGS) -o $(INCLUDES) $(PROG) $(OBJS)


$(BUILD_DIR)/%.o: $(INCL_DIR)/%.h $(SRC_DIRS)/%.cpp
    $(CC) ${CFLAGS} $(CXXFLAGS) $(LVERSION) ${LFLAGS} -c $^ 

.PHONY: progName
clean:
    /bin/rm -rf build/*.o $(PROG) includes/*.gch

This makefile works until is trying to look on objects file, supposedly created on build directory but, in the end, they're created in Makefile's directory, which is an inconvenient since all what i want is to have separated files for organization purposes.

I know that somehow using implicit rules that are using the dst's directory should do the trick, but i think that I'm missing something on the way...

I'm on a Windows 10 machine with WSL for Ubuntu, but this shouldn't be a problem at all for this problem.

Could anyone explain to me what am I missing?


Solution

  • Look at this rule:

    $(BUILD_DIR)/%.o: $(INCL_DIR)/%.h $(SRC_DIRS)/%.cpp
        $(CC) ${CFLAGS} $(CXXFLAGS) $(LVERSION) ${LFLAGS} -c $^ 
    

    Ostensibly it is the rule to build build/foo.o, but the recipe ($(CC)...) actually builds foo.o. There is an easy fix:

    $(BUILD_DIR)/%.o: $(INCL_DIR)/%.h $(SRC_DIRS)/%.cpp
        $(CC) ${CFLAGS} $(CXXFLAGS) $(LVERSION) ${LFLAGS} -c $^ -o $@
    

    Once that works I suggest you make one further change:

    $(BUILD_DIR)/%.o: $(SRC_DIRS)/%.cpp $(INCL_DIR)/%.h
        $(CC) ${CFLAGS} $(CXXFLAGS) $(LVERSION) ${LFLAGS} -c $< -o $@