Make lessons

I was messing around with opencv library for C++ and it’s interface.
Very soon, after I began typing out code from web pages and compiling, I got tired of running the compilation command manually from the terminal.

Not to mention, since I had built opencv from source, I had to explicitly pass -I folder.

Soon, I was wishing I can just run make and get the code to run.

Well, instead of that I figured out a way to run make and just compile and create all object files in the current folder.

Here’s the MakeFile I ended up using:

PROGRAMS_SRC=$(wildcard *.c)
TARGETS=$(patsubst %.c, %,$(PROGRAMS_SRC))
CPPFLAGS=I/usr/local/include/opencv2

all:
$(foreach var,$(PROGRAMS_SRC),g++ $(var) -o $(patsubst %.c, %,$(var)) -$(CPPFLAGS); )

The two key things I learnt were patsubst and foreach. I had seen patsubst and wildcard, while running through LCTHW before.
As the name implies, wildcard keyword is a regex to match a bunch of files.
patsubst is again regex, but this time to replace a set of text.

foreach is simply a way to iterate over a list of values in a variable. I just end up running the g++ command for each of the file.

Note: Am using .c extension here, though i should really be naming the files .cpp and using that in this makefile.
Note2: This assumes all of your code is confined to one file(except for library imports). Otherwise this just won’t work.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s