Search code examples
c++bashmakefilemv

Makefile to move programs to specific directory


I have a makefile that I personally didn't write, and I'm not very good at bash scripting and makefiles in general, so forgive me for my lack of knowledge beforehand;

AS the title states I simply want to move my executables when compiled to a ../bin/ folder. My attempt at this (shamelessy copied from another post here on SO) is given below (i.e. i tried making a phony install which should move the files, but alas it doesnt."

CXX = g++
CC  = g++


# Define preprocessor, compiler, and linker flags. Uncomment the # lines
# if you use clang++ and wish to use libc++ instead of libstd++.
CPPFLAGS  = -std=c++11 -I..
CXXFLAGS  = -g -O2 -Wall -W -pedantic-errors
CXXFLAGS += -Wmissing-braces -Wparentheses -Wold-style-cast 
CXXFLAGS += -std=c++11 
LDFLAGS   = -g -L..
MV = mv
PROG_PATH = ../bin/
#CPPFLAGS += -stdlib=libc++
#CXXFLAGS += -stdlib=libc++
#LDFLAGS +=  -stdlib=libc++

# Libraries
#LDLIBS = -lclientserver
# Targets
PROGS = myserver myclient libclientserver.a   
all: $(PROGS)
# Targets rely on implicit rules for compiling and linking
 # The dependency on libclientserver.a is not defined.
myserver: myserver.o messagehandler.o server.o connection.o database_memory.o database_file.o 
myclient: myclient.o connection.o server.o messagehandler.o
libclientserver.a: connection.o server.o
    ar rv libclientserver.a  connection.o server.o
    ranlib libclientserver.a

# Phony targets
.PHONY: all install clean

all: $(PROGS) install
install: $(MV) $(PROGS) $(PROG_PATH)




# Standard clean
clean:
rm -f *.o $(PROGS)

# Generate dependencies in *.d files
%.d: %.cc
    @set -e; rm -f $@; \
     $(CPP) -MM $(CPPFLAGS) $< > $@.$$$$; \
     sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.$$$$ > $@; \
     rm -f $@.$$$$

# Include the *.d files
 SRC = $(wildcard *.cc)
include $(SRC:.cc=.d)

So how would I best do this? The compiler says

 make: *** No rule to make target `mv', needed by `install'.  Stop.

Solution

  • A makefile rule consists of two parts, a declaration of the rule's dependencies and the commands to invoke.

    The dependencies are listed on the first line of the rule after the colon and the commands to execute are listed on subsequent lines, all indented with tabs.

    Your install rule needs to depend on the programs which you are moving and possibly the destination directory (you may want a rule that creates the destination), but not the mv utility itself as you don't need to build that.

    install: $(PROGS)
        mv $(PROGS) $(PROG_PATH)
    

    Note that although I've used four spaces, the indentation needs to be a tab. As you don't (yet?) have a rule to make PROG_PATH, I've left it out of the dependency list.

    Also note that with this rule, make will have to rebuild your programs if you invoke make twice as they will have moved. You way want to consider using cp or install instead of mv.