Let’s say you want to compile and run the face detection sample code that comes with the OpenCV. This code is located at
OpenCV 2.4.x : /path/to/opencv/samples/c/facedetect.cpp
OpenCV 3 : /path/to/opencv/samples/cpp/facedetect.cpp
Compiling the sample code is super easy using pkg-config. Try this on the command line
pkg-config --cflags --libs opencv
If you have multiple versions of opencv installed, you can provide the path to the opencv.pc file.
pkg-config --cflags --libs /path/to/opencv.pc
The above command lists all the paths to header files and libraries for OpenCV. The instructions below show how to use pkg-config with g++ to compile OpenCV sample code.
Compile and run OpenCV code from the command line on Linux
# For OpenCV 2.4.x cd /path/to/opencv/samples/c/ # For OpenCV 3 cd /path/to/opencv/samples/cpp/ #Compile g++ -ggdb facedetect.cpp -o facedetect `pkg-config --cflags --libs opencv` #run ./facedetect
Compile and run OpenCV code from the command line on Mac OSX
# For OpenCV 2.4.x cd /path/to/opencv/samples/c/ # For OpenCV 3 cd /path/to/opencv/samples/cpp/ #Compile g++ -ggdb `pkg-config --cflags --libs opencv` facedetect.cpp -o facedetect # For OpenCV 3 installed using Homebrew provide the full # path to opencv.pc file g++ -ggdb `pkg-config --cflags --libs /usr/local/Cellar/opencv3/3.1.0_3/lib/pkgconfig/opencv.pc` facedetect.cpp -o facedetect #run ./facedetect
Mac OSX 10.9 and above
If you had compiled OpenCV with libstdc++ you will get the following error.
Undefined symbols for architecture x86_64:
This happens because on OSX 10.9 and above, the compiler links to libc++ by default. You can fix the problem by simply instructing the compiler to use libstdc++ instead —
g++ -ggdb `pkg-config --cflags --libs opencv` -stdlib=libstdc++ facedetect.cpp -o facedetect
Subscribe
If you liked this article, please subscribe to our newsletter and receive a free
Computer Vision Resource guide. In our newsletter we share OpenCV tutorials and examples written in C++/Python, and Computer Vision and Machine Learning algorithms and news.