compiling opencv in c++

  1. Download source files in OpenCV folder and install-opencv.sh script.
  2. By running script file you automatically install needed files for opencv. Run the following code:

    chmod +x install-opencv.sh
    ./install-opencv.sh
    

In case if you install different version of the library please update the first line of version inside the installation script. For more information use this tutorial. Compile it with the next line:

g++ `pkg-config --cflags opencv` example.cpp `pkg-config --libs opencv`

I suggest you use CMake to compile OpenCV with G++, this way is more suitable, I think.

cmake_minimum_required(VERSION 3.1)
project(YOUR_PROJECT_NAME)

set(CMAKE_GXX_FLAGS "-Wall -Wextra -Wconversion  -pedantic -std=gnu11")

find_package(OpenCV REQUIRED)

include_directories(${OpenCV_INCLUDE_DIRS})

add_executable(YOUR_EXCUTABLE YOUR_CODE_SOURCE_FILES)
target_link_libraries(YOUR_EXCUTABLE ${OpenCV_LIBS})

if your development environment does not have pkg-config and because of this the accepted answer by karlphilip is not practical, or, you need to know the minimal set of libraries required to link your application, then assuming code such as

#include <cv.h>
#include <highgui.h>

int main()
{
    return 0;
}

you can add library arguments from the following list sequentially from the top until you find the minimal set of arguments that you need:

  -lopencv_core
  -lopencv_imgproc
  -lopencv_highgui
  -lopencv_ml
  -lopencv_video
  -lopencv_features2d
  -lopencv_calib3d
  -lopencv_objdetect
  -lopencv_contrib
  -lopencv_legacy
  -lopencv_flann

For example, the C source code listed at the top of this post compiles and links cleanly with only

gcc hello.c -o hello \
    -I /usr/include/opencv \
    -L /usr/lib \
    -lopencv_core \
    -lopencv_imgproc

on my old x86_64 Ubuntu 12.04 box.

Assuming C++ code such as

#include "core/core.hpp"
#include "highgui/highgui.hpp"

using namespace cv;
using namespace std;

int main( int argc, char** argv )
{
    return 0;
}

then you would compile and link with

g++ hello.cpp -o hello \
    -I /usr/include/opencv2 \
    -L /usr/lib \
    -lopencv_core \
    -lopencv_imgproc

You need to properly include the headers -I (capital i) and libraries -l (lowercase L).

On the newest OpenCV versions you should do:

#include <cv.h>
#include <highgui.h>

And then try to compile it with:

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

Note: if you execute only pkg-config --cflags --libs opencv in the command line you will see the paths and libraries you need to include in the g++ command line.