使用 OpenCV 编译 C++ 文件时没有这样的文件或目录错误 headers

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

我在使用 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

到我的 PATH,其中 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

PATH无所谓,编译器包含路径需要加上include路径(gcc的-I参数)。或者到 CPLUS_INCLUDE_PATH 环境变量。

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

要成功编译和 link 您的程序,您需要指定头文件的包含路径和 link OpenCV 库的 pre-compileder 路径和列表将 link 编辑的图书馆...

  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 '# OpenCV\nPKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig\nexport PKG_CONFIG_PATH\n' >> ~/.bashrc  
     source ~/.bashrc  
    

以下将为您成功编译和 linked 您的程序:

g++ my_simple_script.cpp `pkg-config --libs opencv` `pkg-config --cflags opencv`
  1. 但显然您还没有这样做.. 因为您正试图指向 non-standard 包含路径。因此,在您的情况下,您需要使用 -I 标志明确指定您的包含路径,并通过 -L 标志明确指定您的 pre-compiled 库路径,并列出您可能想要使用的所有单个库使用 -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>