Buk Lau
Buk Lau

Reputation: 11

Makefile with multiple targets and creates a directory with executable

I don't often use makefiles therefore I only how to make basic ones. I've tried reading on how to solve my issue but I am lost. What I need is a makefile that has two targets all and test. Both of these targets need to compile the program with g++ -std=c+11 -Wall -Werror -ansi -pedantic and the only file that needs to be compiled is main.cpp when the executable is built by the compiler it needs to put the executable in a new directory called bin. And I'm assuming that if I were to use the makefile again it would need to check if bin was already created. I know how to create a simple makefile such as all: g++ -std=c++11 -Wall -Werror -ansi -pedantic main.cpp

That creates an executable named a.out in the current directory, but that's about as far as my knowledge of makefileS go

Upvotes: 1

Views: 501

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118292

All that a Makefile does is specify the build dependencies, and the commands to execute to build those dependencies.

Things like creating the output directories, et. al. is not make's job per se, but rather something that's up to the commands that makes executes to do. Neither does the Makefile specify where the output of the build commands go. That, of course, is specified by the actual commands that get executed. With gcc, for example, the -o option specifies where the compilation output goes. So:

all: bin/main

test: bin/main

bin/main: main.cpp
    mkdir -p bin
    g++ -std=c++11 -Wall -Werror -ansi -pedantic -o bin/main main.cpp 

It's very convenient to use mkdir -p in these situations. If the given directory does not exist, it gets created. If it already exists, mkdir just quietly terminates without an error.

Upvotes: 1

Related Questions