为什么 macOS M2 上的 cmake 找不到 OpenMP?

问题描述 投票:0回答:1

我已经设法在我的 macbook 上编译 OpenMP,但它不会在多线程上运行应用程序。我用了答案here.

这是我的 CMakeList.txt:

cmake_minimum_required(VERSION 3.12)

project(playground)

if(APPLE)
    set(CMAKE_C_COMPILER clang)
    set(CMAKE_CXX_COMPILER clang++)

    if(CMAKE_C_COMPILER_ID MATCHES "Clang\$")
        set(OpenMP_C_FLAGS "-Xpreprocessor -Xclang -fopenmp")
        set(OpenMP_C_LIB_NAMES "omp")
        set(OpenMP_omp_LIBRARY omp)
    endif()

    if(CMAKE_CXX_COMPILER_ID MATCHES "Clang\$")
        set(OpenMP_CXX_FLAGS "-Xpreprocessor -Xclang -fopenmp")
        set(OpenMP_CXX_LIB_NAMES "omp")
        set(OpenMP_omp_LIBRARY omp)
    endif()

endif()

find_package(OpenMP REQUIRED)

add_executable(helloworld openmp.cpp)

set(OMPIncludeDirectory "/opt/homebrew/opt/libomp/include")
target_include_directories(helloworld PUBLIC ${OMPIncludeDirectory} )

target_link_libraries(helloworld PUBLIC /opt/homebrew/opt/libomp/lib/libomp.dylib)

这个编译但应用程序不在多个线程上运行(只有一个)。

如果我没有明确提供库路径而是将最后一行更改为:

target_link_libraries(helloworld PUBLIC OpenMP::OpenMP_CXX)

它给我链接错误:

cmake --build build
[ 50%] Linking CXX executable helloworld
ld: library not found for -lomp
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [helloworld] Error 1
make[1]: *** [CMakeFiles/helloworld.dir/all] Error 2
make: *** [all] Error 2

我尝试使用以下命令手动编译并且它有效。可执行文件也在多个线程上运行:

c++ openmp.cpp -I/opt/homebrew/opt/libomp/include -L/opt/homebrew/opt/libomp/lib/ -lomp -Xclang -fopenmp

这是我的简单测试程序:

// OpenMP program to print Hello World
// using C language

// OpenMP header
#include <omp.h>

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{

    // Beginning of parallel region
    #pragma omp parallel
    {

        printf("Hello World... from thread = %d\n",
            omp_get_thread_num());
    }
    // Ending of parallel region
}

我在这里错过了什么?请帮助。

c++ c macos cmake openmp
1个回答
0
投票

如果你使用

find_package(OpenMP REQUIRED)

你不应该明确地拼出其他选项:

target_link_libraries( program PUBLIC OpenMP::OpenMP_CXX)

(我听说 Apple 的本地编译器可能不随 OpenMP 一起提供。我使用 gcc12,就 OpenMP 功能而言,它是最新的,并且很容易从 macports 或 homebrew 等包管理器获得。 )

© www.soinside.com 2019 - 2024. All rights reserved.