1

I have the following Makefile:

CXX       = g++
CXXFLAGS  = -Wall -g
SOURCES  := divisor.cpp multiplier.cpp
OBJECTS  := ${SOURCES:.cpp=.o}

%.o: %.cpp 
        $(CXX) -c $(CXXFLAGS) $< -o $@

%: %.o $(OBJECTS)
        $(CXX) $(CXXFLAGS) $@.o -o $@.out

$(OBJECTS): %.o: %.cpp
        $(CXX) -c $(CXXFLAGS) $< -o $@
clean:
        rm -f *.o

What I want this make file is the following: If I add a source file called 123.cpp to the working directory, I want it to generate its object file and then link the compiled sources specified in $(SOURCES), this means:

g++ -c -Wall -g 123.cpp
g++ multipler.o divisor.o 123.o -o 123

If multiplier.cpp or divisor.cpp has to be generated or updated, I want make to do it.

But I'm failing, because divisor.o and multiplier.o are not automatically generated

How may I achieve this?

Edit

Just to clarify, there are two types of source code files in the working directory: divisor.cpp, multipler.cpp is one type, and any other file, say, 123.cpp is the other type. In a sense, divisor.cpp and multiplier.cpp are requisites to the other source files.

I want to automate the process of compiling the prerequisites and link them when compiling the other files

g++ -c multiplier.cpp
g++ -c divisor.cpp
g++ -c -Wall -g 123.cpp
g++ multipler.o divisor.o 123.o -o 123
Jorge Lavín
  • 937
  • 8
  • 22
  • 1
    Firstly, you have no rule depending on ``$(SOURCES)`` in place. You need something similar to what you did with ``$(OBJECTS)`` – BitTickler Apr 04 '15 at 17:53
  • 1
    You didn't specify any final target depending on `$(OBJECTS)`? – πάντα ῥεῖ Apr 04 '15 at 17:56
  • Does not the target `$(OBJECTS)` qualify as a rule for `$(SOURCES)` implicitly? The final target depending on `$(OBJECTS)` is not `%:%.o $(OBJECTS)` ? Thanks both – Jorge Lavín Apr 04 '15 at 17:59
  • 1
    When you say "add a source file called `123.cpp`", do you mean put that file into the working directory, or add "123.cpp" to the makefile somehow? – Beta Apr 04 '15 at 22:38
  • I mean "add a source file called `123.cpp`" i will edit the question accordingly. Thanks for the remark – Jorge Lavín Apr 04 '15 at 22:42
  • possible duplicate of [Makefiles - Compile all .cpp files in src/ to .o's in obj/, then link to binary in /](http://stackoverflow.com/questions/2908057/makefiles-compile-all-cpp-files-in-src-to-os-in-obj-then-link-to-binary) – CinchBlue Apr 05 '15 at 03:51

1 Answers1

1

Use the wildcard function:

SOURCES := $(wildcard *.cpp)

Then, you can remove your "special" source files:

SPECIAL_SOURCES := divisor.cpp multiplier.cpp
SOURCES := $(filter-out $(SPECIAL_SOURCES),$(SOURCES))

And change your rules to build the stuff you actually want:

$(SPECIAL_OBJECTS) := $(SPECIAL_SOURCES:.cpp=.o)
$(BINARIES) := $(patsubst .cpp,,$(SOURCES))

$(SPECIAL_OBJECTS) : %.o : %.cpp
    $(CXX) $(CXXFLAGS) -c -o $@ $^

$(BINARIES) : % : %.cpp $(SPECIAL_OBJECTS)
    $(CXX) $(CXXFLAGS) -o $@ $^
Carl Norum
  • 219,201
  • 40
  • 422
  • 469