使用 OpenCV 标头编译文件时C++不会出现此类文件或目录错误

No such file or directory error when compiling C++ file with OpenCV headers

本文关键字:文件 错误 OpenCV 编译 使用 C++      更新时间:2023-10-16

我在Red Hat Linux上。我对C++文件中的包含有一些(可能是新手)问题。我创建了以下简单的 OpenCV 脚本,

#include "opencv2/highgui/highgui.hpp"
using namespace cv;
int main(int argc, char ** argv){
    Mat img = imread( argv[1], -1 );
    if ( img.empty() ) return -1;
    namedWindow( "Example1", cv::WINDOW_AUTOSIZE );
    imshow( "Example1", img );
    waitKey( 0 );
    destroyWindow( "Example1" );
}

然后在我输入的终端中

g++ my_simple_script.cpp

并得到错误

newfile.cpp:1:39: error: opencv2/highgui/highgui.hpp: No such file or directory
newfile.cpp:3: error: 'cv' is not a namespace-name
newfile.cpp:3: error: expected namespace-name before ';' token
newfile.cpp: In function 'int main(int, char**)':
newfile.cpp:6: error: 'Mat' was not declared in this scope
newfile.cpp:6: error: expected ';' before 'img'
newfile.cpp:7: error: 'img' was not declared in this scope
newfile.cpp:8: error: 'cv' has not been declared
newfile.cpp:8: error: 'namedWindow' was not declared in this scope
newfile.cpp:9: error: 'img' was not declared in this scope
newfile.cpp:9: error: 'imshow' was not declared in this scope
newfile.cpp:10: error: 'waitKey' was not declared in this scope
newfile.cpp:11: error: 'destroyWindow' was not declared in this scope

我添加了

/home/m/maxwell9/2.4.3/include

到我的路径,其中 2.4.3 表示我正在使用的 OpenCV 版本。当我打字时

echo $PATH

明白了

/opt/apps/jdk1.6.0_22.x64/bin:/apps/smlnj/110.74/bin:/usr/local/cuda/bin:/sbin:/bin:/usr/sbin:/usr/bin:/apps/weka/3.7.12:/home/m/maxwell9/bin:/home/m/maxwell9/2.4.3/include

我确认有一个文件

/home/m/maxwell9/2.4.3/include/opencv2/highgui/highgui.hpp

仅添加包含路径只能解决编译问题。您仍然会看到链接器错误。(添加包含路径的正确方法是使用 -I 标志,PATH 不用于此..)

要成功编译和链接程序,您需要指定头文件的包含路径和预编译的 OpenCV 库的链接器路径以及要链接的库列表...

    标准
  1. 方式,将 openCV 安装到标准安装目录,使用以下顺序

     sudo make install (from your OpenCV build library)
     echo '/usr/local/lib' | sudo tee -a /etc/ld.so.conf.d/opencv.conf
     sudo ldconfig
     printf '# OpenCVnPKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfignexport PKG_CONFIG_PATHn' >> ~/.bashrc  
     source ~/.bashrc  
    

以下内容将为您成功编译和链接您的程序:

g++ my_simple_script.cpp `pkg-config --libs opencv` `pkg-config --cflags opencv`
  1. 但显然你没有这样做......因为你试图指向一个非标准的包含路径。因此,在您的情况下,您需要使用 -I 标志显式指定包含路径,并通过-L标志明确指定预编译库路径,并使用 -l<name_of_library> 列出您可能想要使用的所有单个库

    g++ my_simple_script.cpp -I /home/m/maxwell9/2.4.3/include -L /home/m/maxwell9/2.4.3/<your build directory name>/lib/ -lopencv_core
    

(您可能需要的其他 openCV 库列表必须使用格式附加到上面的命令中:-l<name of the lib you need>

PATH 无关紧要,您需要将包含路径添加到编译器包含路径(gcc 的 -I 参数)。或到CPLUS_INCLUDE_PATH环境变量。