0

I have the following makefile snippet to compile my C++ project.

obj/%.o: src/%.cpp
    $(CXX) $(CFLAGS) -c $< -o $@

Now I want to link the .o files. But I want to be able to just call the rule name of the link, like make build/main, in order to compile AND link.

Neither this:

build/main: $(wildcard obj/*.o)
    $(CXX) $^ -o $@

works, as it only links and does not compile, as I would expect by this answer;

nor this:

build/main: obj/%.o
    $(CXX) $^ -o $@

with the error:

No rule to make target 'obj/%.o', needed by 'build/main'. Stop.

even though it is needed.

Community
  • 1
  • 1
Post Self
  • 1,471
  • 2
  • 14
  • 34
  • 1
    The `build/main: $(wildcard obj/*.o)` won't work, because the wildcard will be expanded when the rule is first read (before the .o's are built, and before they exist on the filesystem, so it would expand to empty). – blackghost Apr 10 '17 at 15:54

1 Answers1

3
SOURCES := $(wildcard src/*.cpp)
OBJECTS := $(patsubst src/%.cpp, obj/%.o, $(SOURCES))

build/main: $(OBJECTS)
    $(CXX) $^ -o $@
Beta
  • 96,650
  • 16
  • 149
  • 150