3

I have a makefile for a C++ project that compiles and creates an executable for the program, and then runs that executable. The problem is, I want the executable to be run every time I use the make command, but if there have been no changes to the source that need to be recompiled, make will come back with “make: nothing to be done.” Is there a way to format the makefile so that it will compile and run if compilation is needed, otherwise just run the executable?

Catmitt98
  • 33
  • 3
  • Welcome to Stack Overflow. Please [edit] your question to include the Google search results you researched before asking this question, and why those results didn't answer your question. – Jonny Henly Sep 17 '19 at 16:31
  • Can you provide an working (representative) example of what you have? – Galik Sep 17 '19 at 17:02
  • Would running the executable without the makefile be easier? – Thomas Matthews Sep 17 '19 at 17:04
  • @Thomas Matthews it’s for grading of a homework assignment. Basically she said we can write our code for the assignment in whatever language we want, as long as it builds and runs on our campus computers, we’d just have to include a makefile to do so. Her auto grader script will simply run make on all of our makefiles and it should build and run using just the makefile, so she doesn’t have to do anything language specific since the language choices are endless. – Catmitt98 Sep 18 '19 at 17:15
  • C++ is completely irrelevant here. – Ulrich Eckhardt Sep 18 '19 at 18:23

1 Answers1

3

You can simply add a new target to run the program and make that target depend on the creation of the program. If you make that target a dependency of the default target (all:) it will always run the program after a successful build.

Like this:

SOURCES = ./src/main.cpp


OBJECTS = ./bin/main.o


# default target to build hello executable & run it if successful
all: hello run

hello: $(OBJECTS)
    $(CXX) -o $@ $^

bin/%.o : src/%.cpp
    $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) -o $@ $< $(LDFLAGS)

run: hello
    ./hello

clean:
    @rm -rf hello $(OBJECTS)

.PHONY: all run clean

Note: There is nothing special about the target name "run". I could have called it "wibble".

Galik
  • 47,303
  • 4
  • 80
  • 117