Xcode is a complete developer toolset for creating apps for Mac, iPhone, iPad, Apple Watch, and Apple TV. Xcode brings user interface design, coding, testing, debugging, and submitting to the App Store all into a unified workflow.
Here’s a tutorial to setting up OpenCV and C++ environment for Xcode on macOS.
- Install Homebrew
Aptly titled “The missing package manager for macOS” is enough said. Homebrew is the macOS equivalent of the Ubuntu/Debian-based
/usr/bin/ruby -e $(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)
- Install OpenCV
Simply we use brew to install the latest pre-compiled OpenCV to our computer:
brew install opencv
- Install pkg-config
The pkg-config is a helper tool used when compiling applications and libraries. It helps you insert the correct compiler options on the command line rather than hard-coding values. This will be helpful for finding the correct linker flags for OpenCV. This will be more clear in the subsequent steps.
brew install pkg-config
- View OpenCV linker flags
To view the linker flags for OpenCV, we should find
.pc file first. It’s common to see this file in:
Then view the linker flags by specifing the location of opencv.pc file:
pkg-config --cflags --libs <path/to/opencv.pc>
Running code in the terminal, the code should be compiled first:
g++ $(pkg-config --cflags --libs <path/to/opencv.pc>) -std=c++17 main.cpp -o main.o
Then run the binary:
chmod +x main.o
Before following the below steps to run OpenCV C++ code in Xcode, a C++ project in Xcode should be created first.
- Click on
File > New > Project
- Under Choose a template for new project click on macOS
- Under Application click on Command Line Tool
- Get the above screen. Fill in the details and set the Language to C++.
- Click on
Set Header Search Paths
- To set Header Search Path in Xcode, first click on the Xcode project, then go to Build Settings and then search for Header Search Paths.
- Set the Header Search Path to the path of OpenCV include folder:
Set Library Search Paths
- In this case, follow steps similar to Set Header Search Paths above but search for Library Search Paths in the search bar.
- Set the Library Search Path to the path of OpenCV library folder.
Set Other Linker Flags
- Search for Other Linker Flags in the search bar.
- Set the other linker flags with all the flag values obtained after running
To allow camera access, first click on the Xcode project, then go to TARGETS > Signing & Capabilities and check Disable Library Validation, Debugging Tool, Audio Input and Camera.
Info.plist, add access requirement details:
Key: Privacy - Camera Usage Description
Then go to TARGETS > Build Phases > Copy Files, select Destnation to Products Directory, leave Subpath blank and click
+ to select file