John Hamlett IV John Hamlett IV - 1 month ago 9
C++ Question

Make file building all objects files from same source file

I have a project that contains a obj and a src subfolder.

When I run make with the following Makefile, it builds each .o with the same src.

CXX = g++
CXXINCDIRS = -I./ext/glui/include -I.
CXXLIBDIR = /usr/lib/
SRCDIR = ./src
OBJDIR = ./obj
INCDIR = ./include
BINDIR = ./bin
EXE = $(BINDIR)/brushwork
CXXFLAGS += -W -Wall -Wextra -Weffc++ -std=c++11 $(CXXINCDIRS)
SRC_CXX = $(wildcard $(SRCDIR)/*.cc)
OBJECTS_CXX = $(patsubst $(SRCDIR)/%.cc, $(OBJDIR)/%.o, $(SRC_CXX))
LIBRARY_CXX = -lglut -lGL -lGLU -L/usr/lib -lglui

$(OBJDIR)/%.o: $(SRCDIR)/%.cc
g++ -o $@ -c $<

$(EXE): $(OBJECTS_CXX) | $(BINDIR)
$(CXX) $(CXXFLAGS) $(CXXINCDIRS) -o $@ $^ $(CXXLIBDIR) $(LIBRARY_CXX)

$(OBJECTS_CXX): $(SRC_CXX) | $(OBJDIR)
$(CXX) $(CXXFLAGS) -c -o $@ $<

$(OBJDIR)/%.o: $(SRC_CXX) $(INCDIR)/%.h | $(OBJDIR)
$(CXX) $(CXXFLAGS) -c -o $@ $<

$(BINDIR) $(OBJDIR):
mkdir -p $@


When I run the command

make -B -n


I get

mkdir -p obj
g++ -W -Wall -Wextra -Weffc++ -std=c++11 -I./ext/glui/include -I. -c -o obj/tool.o src/tool.cc
g++ -W -Wall -Wextra -Weffc++ -std=c++11 -I./ext/glui/include -I. -c -o obj/base_gfx_app.o src/tool.cc
g++ -W -Wall -Wextra -Weffc++ -std=c++11 -I./ext/glui/include -I. -c -o obj/color_data.o src/tool.cc
g++ -W -Wall -Wextra -Weffc++ -std=c++11 -I./ext/glui/include -I. -c -o obj/main.o src/tool.cc
g++ -W -Wall -Wextra -Weffc++ -std=c++11 -I./ext/glui/include -I. -c -o obj/pixel_buffer.o src/tool.cc
g++ -W -Wall -Wextra -Weffc++ -std=c++11 -I./ext/glui/include -I. -c -o obj/brushwork_app.o src/tool.cc
mkdir -p bin
g++ -W -Wall -Wextra -Weffc++ -std=c++11 -I./ext/glui/include -I. -I./ext/glui/include -I. -o bin/brushwork obj/tool.o obj/base_gfx_app.o obj/color_data.o obj/main.o obj/pixel_buffer.o obj/brushwork_app.o /usr/lib/ -lglut -lGL -lGLU -L/usr/lib -lglui


I am not sure why each obj file is being built with the same src file.

I have tried $(SRCDIR)/%.cc but make complains that there is no recipe for $(SRCDIR)/%.cc

How can I have make build each src file it's respective src file?

Answer

For this:

$(OBJDIR)/%.o: $(SRC_CXX)  $(INCDIR)/%.h | $(OBJDIR)
    $(CXX) $(CXXFLAGS) -c -o $@ $<

I think you need this:

$(OBJDIR)/%.o: $(SRCDIR)/%.cc $(INCDIR)/%.h
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c -o $@ $<

I'm not sure what this does:

$(OBJECTS_CXX):  $(SRC_CXX) | $(OBJDIR)
    $(CXX) $(CXXFLAGS) -c -o $@ $<

I suspect you should remove it.

And I think you should also remove this:

$(OBJDIR)/%.o: $(SRCDIR)/%.cc
    g++ -o $@ -c $<

It looks like you had 3 different rules to build your objects (unless I read it wrong).

Comments