OliP14
OliP14

Reputation: 31

Cannot open source file error with vcpkg on vscode mac

I'm trying to use external libraries (specifically opencv) with C++ but I'm having some trouble. It seems like using vcpkg is the easiest way to go about this. So far I've followed these tutorials: https://www.youtube.com/watch?v=b7SdgK7Y510 and https://www.youtube.com/watch?v=iZeK3Ie5Fz0 but I keep getting these errors when I try to include a file:

cannot open source file "opencv2/core.hpp"

'opencv2/core.hpp' file not found

The quick fix provided by vscode says to install opencv through vcpkg but I've already done that. I've linked vcpkg according to the tutorials and included the path to the cmake toolchain file in my settings.json file.

Here is the change I made to my settings.json file:

{
"cmake.configureSettings": {
    "CMAKE_TOOLCHAIN_FILE": "/Users/oliverpasquesi/coding/dev/vcpkg/scripts/buildsystems/vcpkg.cmake"
}

}

Here is the CMakeLists.txt file (it is the same as the one from the 2nd tutorial listed):

cmake_minimum_required(VERSION 3.0.0)
project(photoText.cpp VERSION 0.1.0)

add_executable(photoText.cpp main.cpp)

Here is the includePath portion of the c_cpp_properties.json file (including the 2nd path doesn't make any difference in the errors being thrown):

"includePath": [
            "${default}",
            "/Users/oliverpasquesi/coding/dev/vcpkg/installed/x64-osx/include/opencv2/**"
        ]

If it's useful, I'm using vscode 1.49.2 on a mac running Darwin x64 21.5.0.

I appreciate the help!

Upvotes: 0

Views: 1116

Answers (1)

Augustin Popa
Augustin Popa

Reputation: 1543

You need to reference your library in the CMakeLists.txt file as well, since that's the file CMake uses to prepare your project for a build.

A modern way to do this is to add two lines:

  1. A find_package() line to find the libraries you are using. As you already referenced the vcpkg.cmake toolchain file, CMake should be able to find any libraries already installed by vcpkg when you add that line. See https://cmake.org/cmake/help/latest/command/find_package.html for documentation.
  2. A target_link_libraries() line that lists libraries to link against your project. See the CMake documentation here: https://cmake.org/cmake/help/latest/command/target_link_libraries.html

As you are using the opencv library, you may want to look at the answers to this question as well: Linking Opencv in a project using cmake

Specifically, try adding these lines to your CMakeLists.txt:

find_package(OpenCV REQUIRED)
target_link_libraries(photoText.cpp ${OpenCV_LIBS})

vcpkg documentation on its CMake integration (for additional reference): https://vcpkg.io/en/docs/users/buildsystems/cmake-integration.html

Hopefully this helps!

Disclaimer: I work on the vcpkg tool.

Upvotes: 1

Related Questions