Makefile that compiles all cpp files in a directory into a separate executable

Now I'm learning C ++. I want a makefile that compiles all cpp files in the current directory to separate executable files. For example:

There are 3 C ++ files in the directory, for example examp1.cpp, examp2.cpp and examp3.cpp . I want a makefile that will compile and link them, and give examp1.exe, examp2.exe and examp3.exe

I created a bash script to compile them all and create exes, but I think; this is not the exact way to do this.

I have a Makefile for ".c", but this does not seem to work here. It creates only object files and does not link them. It looks like this:

SRCS=$(wildcard *.c) OBJS=(SRCS:.c=.o) all: $(OBJS) 

The above code compiles all new and changed โ€œ.cโ€ files into โ€œ.oโ€ files with the same name in the current directory.

The bash script I use to create executables is:

 for i in ./*.cpp do g++ -Wno-deprecated $i -o `basename $i .cpp`".exe" done 

This means that I want all the โ€œ.cppโ€ files to be placed in this directory using a simple โ€œmake allโ€ or something similar that it should compile.

+7
source share
4 answers

Minimal Makefile that does what you want:

 #Tell make to make one .out file for each .cpp file found in the current directory all: $(patsubst %.cpp, %.out, $(wildcard *.cpp)) #Rule how to create arbitary .out files. #First state what is needed for them eg additional headers, .cpp files in an include folder... #Then the command to create the .out file, probably you want to add further options to the g++ call. %.out: %.cpp Makefile g++ $< -o $@ -std=c++0x 

You will need to replace g ++ with the compiler you are using, and possibly configure some platform parameters, but the Makefile itself should work.

+16
source

This is the makefile that I use

 CC = gcc CFLAGS = -g -O2 -std=gnu99 -static -Wall -Wextra -Isrc -rdynamic -fomit-frame-pointer all: $(patsubst %.c, %.out, $(wildcard *.c)) %.out: %.c Makefile $(CC) $(CFLAGS) $< -o $@ -lm clean: rm *.out 

You have to paste it somewhere in your house and whenever you change the dirctory, just copy it there. I use an alias in my ~ / .basrc to copy it

 alias get_makefile_here='cp ~/Makefile ./' 

Just hit make and bam, you're done. Also note that after you are done with old files, it will not restore their executable file.

+3
source

The simplest makefile you can create that can work for you is:

 all: examp1.exe examp2.exe examp3.exe 

This will use the default rules to create three programs.

+1
source

My answer is based on @Haatschii's answer

I do not prefer the .out prefix for my binaries. In addition, I used my existing Make syntax to do the cleanup as well.

 CXX=clang++ CXXFLAGS=-Wall -Werror -std=c++11 all: $(patsubst %.cpp, %.out, $(wildcard *.cpp)) %.out: %.cpp Makefile $(CXX) $(CXXFLAGS) $< -o $(@:.out=) clean: $(patsubst %.cpp, %.clean, $(wildcard *.cpp)) %.clean: rm -f $(@:.clean=) 
0
source

All Articles