文件名末尾时出现 g++ 链接错误

g++ linking error when filename at the end

我正在尝试编译一个使用 opencv 库的 test.cpp 文件。我运行 g++命令如下:

g++ test.cpp -o test -I/usr/local/include/opencv4 -L/usr/local/lib -lopencv_core -lopencv_imgproc -lopencv_imgcodecs -lopencv_highgui

这成功生成了一个名为 test 的可执行文件,它按照我想要的方式工作。

然而,当我尝试像这样编译时(这也是 makefile 编译给定 CFLAGS 和 LDFLAGS 作为变量的方式):

g++ -I/usr/local/include/opencv4 -L/usr/local/lib -lopencv_core -lopencv_imgproc -lopencv_imgcodecs -lopencv_highgui test.cpp -o test

它给我以下错误:

/usr/bin/ld: /tmp/cc58r16w.o: in function `main':
test.cpp:(.text+0x62): undefined reference to 

`cv::imread(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, int)'
/usr/bin/ld: test.cpp:(.text+0xc0): undefined reference to `cv::namedWindow(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, int)'
/usr/bin/ld: test.cpp:(.text+0x139): undefined reference to `cv::imshow(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, cv::_InputArray const&)'
/usr/bin/ld: test.cpp:(.text+0x170): undefined reference to `cv::waitKey(int)'
/usr/bin/ld: test.cpp:(.text+0x181): undefined reference to `cv::Mat::~Mat()'
/usr/bin/ld: test.cpp:(.text+0x256): undefined reference to `cv::Mat::~Mat()'
collect2: error: ld returned 1 exit status

如果这是我忽略的愚蠢错误,我提前道歉,但我似乎找不到解决方案。

感谢帮助。谢谢

Unix 系统中的链接器不会返回文件列表来解析名称;他们只往前走。因此,即使链接器看到了定义这些名称的文件,它也没有做笔记,并且当以后使用这些名称时,它不记得它之前看到过它们。通常,您必须将库名称放在命令行的末尾。