为 macOS-x86_64 构建,但尝试链接为 macOS-arm64 构建的文件

时间:2021-01-19 19:31:07

标签: c++ macos opencv g++

我用 C++ 和 OpenCV 写了一段代码:

#include <iostream>
#include <time.h>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>

using namespace std;

int main()
{
    ...
    return 0;
}

然后我尝试在终端上运行我的代码并使用 g++ 构建:

g++ $(pkg-config --cflags --libs opencv) -std=c++11  yourFile.cpp -o yourFileProgram

但我收到此错误:

...
ld: warning: ignoring file /opt/homebrew/Cellar/opencv/4.5.1_2/lib/libopencv_core.dylib, building for macOS-x86_64 but attempting to link with file built for macOS-arm64
ld: warning: ignoring file /opt/homebrew/Cellar/opencv/4.5.1_2/lib/libopencv_photo.dylib, building for macOS-x86_64 but attempting to link with file built for macOS-arm64
Undefined symbols for architecture x86_64:
  "cv::Mat::Mat()", referenced from:
      _main in cv_test-ff1014.o
  "cv::Mat::~Mat()", referenced from:
      _main in cv_test-ff1014.o
  "cv::Mat::operator=(cv::Mat&&)", referenced from:
      _main in cv_test-ff1014.o
  "cv::imread(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, int)", referenced from:
      _main in cv_test-ff1014.o
  "cv::imwrite(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, cv::_InputArray const&, std::__1::vector<int, std::__1::allocator<int> > const&)", referenced from:
      _main in cv_test-ff1014.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,简短的回答是 Apple 改用 libc++ 而不是 libstdc++。如果你想按照你提到的方式编译它(通过控制台 g++),那么 the answer is here.

此外,您在标记中提到了 g++,但要确保 you understand that gcc is alias of clang,并且要使用 g++ 编译器,您必须打印 g++-10

示例中提供的通过终端编译 OpenCVg++ 的方法是 described here

在 macOS 上包含 OpenCV 库的最佳方法是通过自制的 opencv 库安装,然后生成 CMakeLists.txt。可能的例子:

cmake_minimum_required(VERSION 3.17)
project(PROJECT_NAME)
find_package(OpenCV REQUIRED )
include_directories( ${OpenCV_INCLUDE_DIRS} )

set(CMAKE_CXX_STANDARD 17)

#set(CMAKE_CXX_COMPILER "/usr/local/bin/g++-10" CACHE STRING "C++ compiler" FORCE)
#set(CMAKE_C_COMPILER "/usr/local/bin/gcc-10" CACHE STRING "C compiler" FORCE)

add_executable(PROJECT_NAME main.cpp)
target_link_libraries(PROJECT_NAME ${OpenCV_LIBS} )

请注意,如果您要强制使用 g++-10(取消注释集结构),那么将会出现 problem like described here
我认为 OpenCV 没有 arm 更新,然后忽略警告并尝试类似的操作。