Question

Unfortunately this is a very simplistic question but I can't seem to find the answer. I'm just getting back into c++ programming and figure I'd retrain my rusty skills with some project euler questions. I was planning on quickly doing the first 10 tonight but ran into a problem before I started with the makefile (somewhat embarrassing I know).

To the point. I created a directory structure like so:

 ✗ tree
.
├── bin
├── inc
├── Makefile
├── obj
└── src
    └── 1.cpp

My thinking was that I would create a bunch of separate files in src and compile them to bin but I have been unable to figure out how to do that. (Is a makefile a bad fit for this? I assumed it would be sufficient).

I thought I would be able to call it with syntax like so:

make 1

which would compile bin/1 and obj/1.o from src/1.cpp.

My attempt so far is like so:

CC=gcc
CFLAGS=-Wall -g -std=c11
OBJDIR=obj
SRCDIR=src
BINDIR=bin

$(OBJDIR)/%.o: $(SRCDIR)/%.cpp
        $(CC) -c -o $@ $< $(CFLAGS)


clean:
        rm -f $(BINDIR)/* $(OBJDIR)/*

But this results in:

✗ make 1
make: *** No rule to make target '1'.  Stop.

I feel like I'm missing something obvious and am tempted to resort to a bash script but that feels like cheating and not using the right tool for the job. I'm guessing the problem is that I want to call Make on different files.

Was it helpful?

Solution

You need another rule to build the binaries:

$(BINDIR)/%: $(OBJDIR)/%.o
        $(CC) -o $@ $< $(CFLAGS) # you don't actually need that line!

And then one shortcut rule:

TARGETS=$(patsubst $(SRCDIR)/%.cpp,%,$(wildcard $(SRCDIR)/*.cpp))

$(TARGETS): %: $(BINDIR)/%
.PHONY: $(TARGETS)

Which allows you to say make 1 instead of make bin/1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top