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

Saj*_*mmi 10 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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

但我收到此错误:

...
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)
Run Code Online (Sandbox Code Playgroud)

Mik*_*ike 7

我遇到了同样的问题,简短的答案是苹果改用libc++使用libstdc++. 如果您想按照您提到的方式编译它(通过控制台 g++),那么答案就在这里

另外,您在标签中提到过g++,但请确保您了解 gcc 是 clang 的别名,并且要使用g++编译器,您必须打印g++-10

这里描述了您在示例中提供的通过终端进行编译的OpenCV方法g++

在 macOS 上包含OpenCVlib 的最佳方法是通过 homebrew opencv lib 安装,然后生成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} )
Run Code Online (Sandbox Code Playgroud)

请注意,如果您强制使用g++-10(取消注释集结构),则会出现此处描述的问题
我认为没有OpenCV更新arm,然后忽略警告并尝试类似的操作。