Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Makefile to Compile OpenCV Code in C++ on Ubuntu/Linux

I am learning OpenCV using Learning OpenCV book.

One problem I am facing while compiling the code is that I have to write a long command to compile and get the executable.

This is the command I am using

g++ `pkg-config –cflags opencv` file_name.cpp -o output_file `pkg-config –libs opencv`

I am no Make expert but I think I can eliminate writing that long command using make. Before that I should explain my work flow. I have created a directory called opencv in my home directory (~/opencv/). I am reading the book section by section and coding the examples or exercises into new cpp source code files in that directory. So I don't know the names of the files before hand.

Now what I want make to do is,

Suppose I have coded a new file named facedetect.cpp in my opencv directory, and if I call make like this

make facedetect

then I want make to execute the following command for me

g++ `pkg-config --cflags opencv` facedetect.cpp -o facedetect `pkg-config --libs opencv`

so that whenever I make a new file named abc.cpp, I will execute make abc so that I can run

$ ./abc

at my command line to test my abc.cpp

Please give that make file so that I can save the frustration of typing that long command each time.

PS: I have Googled for help on this and found this on using CMake but I could not understand what that does. Kindly also explain how can I use CMake for the same task.

like image 721
spv Avatar asked Mar 26 '12 10:03

spv


1 Answers

You can create a file called Makefile in you working directory like this:

CFLAGS = `pkg-config --cflags opencv`
LIBS = `pkg-config --libs opencv`

% : %.cpp
        g++ $(CFLAGS) $(LIBS) -o $@ $<

then you can use this file for all your single-file programms. Just call make with the basename of the file you want to compile. For facedetect.cpp that would be

make facedetect

Here some more details:

The general format of a makefile is like this:

target : dependecy1 dependenc2 ...
    command that generates the target

So for your example you could write:

facedetect : facedetect.cpp
    g++  $(CFLAGS) $(LIBS) -o facedetect facedetect.cpp

For each new example you can now create a new target. But you can also make it more general:

% : %.cpp
    g++  $(CFLAGS) $(LIBS) -o $@ $<

Here % matches any nonempty substring. The automatic variables $@ and $< substitute the names of the target file and the source file. For more information you can consult the make documentation.

like image 175
sietschie Avatar answered Sep 20 '22 18:09

sietschie