John Hamlett IV John Hamlett IV - 1 year ago 191
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)/, $(OBJDIR)/%.o, $(SRC_CXX))
LIBRARY_CXX = -lglut -lGL -lGLU -L/usr/lib -lglui

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


$(CXX) $(CXXFLAGS) -c -o $@ $<

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

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/
g++ -W -Wall -Wextra -Weffc++ -std=c++11 -I./ext/glui/include -I. -c -o obj/base_gfx_app.o src/
g++ -W -Wall -Wextra -Weffc++ -std=c++11 -I./ext/glui/include -I. -c -o obj/color_data.o src/
g++ -W -Wall -Wextra -Weffc++ -std=c++11 -I./ext/glui/include -I. -c -o obj/main.o src/
g++ -W -Wall -Wextra -Weffc++ -std=c++11 -I./ext/glui/include -I. -c -o obj/pixel_buffer.o src/
g++ -W -Wall -Wextra -Weffc++ -std=c++11 -I./ext/glui/include -I. -c -o obj/brushwork_app.o src/
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)/ but make complains that there is no recipe for $(SRCDIR)/

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

Answer Source

For this:

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

I think you need this:

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

I'm not sure what this does:

    $(CXX) $(CXXFLAGS) -c -o $@ $<

I suspect you should remove it.

And I think you should also remove this:

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download