Clion 和 OpenMP

Clion and OpenMP

我正在学习并行计算,并开始了我的 OpenMP 和 C 之旅。

我一直在配置 Clion,但没有成功。

#include <stdio.h>
#include <omp.h>

int main() {
    #pragma omp parallel
{ 
   int n = omp_get_num_threads();
   int tid = omp_get_thread_num();
    printf("There are %d threads. Hello from thread %d\n", n, tid);
};

/*end of parallel section */
printf("Hello from the master thread\n");

}

但是我收到这个错误:

函数中main': C:/Users/John/CLionProjects/Parallelexamples/main.c:6: undefined reference toomp_get_num_threads' C:/Users/John/CLionProjects/Parallelexamples/main.c:7: 对“omp_get_thread_num”的未定义引用 collect2.exe:错误:ld 返回了 1 个退出状态 mingw32-make.exe[2]: * [Parallelexamples.exe] 错误 1 CMakeFiles\Parallelexamples.dir\build.make:95:目标 'Parallelexamples.exe' 的配方失败 mingw32-make.exe[1]: * [CMakeFiles/Parallelexamples.dir/all] 错误2 CMakeFiles\Makefile2:66:目标 'CMakeFiles/Parallelexamples.dir/all' 的配方失败 Makefile:82:目标 'all' 的配方失败 mingw32-make.exe: *** [所有] 错误 2

我按照说明制作了我的 CMakeListtxt 文件,如下所示:

cmake_minimum_required(VERSION 3.8)
project(Parallelexamples)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu11 -fopenmp")


set(SOURCE_FILES main.c)
add_executable(Parallelexamples ${SOURCE_FILES})

我是不是漏掉了什么?

首先,由于您使用的是 CMake,请利用 FindOpenMP 宏:https://cmake.org/cmake/help/latest/module/FindOpenMP.html

cmake_minimum_required(VERSION 3.8)
project(Parallelexamples)

其次,您似乎没有链接到 OpenMP 运行时库。您不仅必须传递 openmp 编译标志,还必须传递正确的链接器标志:

set_target_properties(Parallelexamples LINK_FLAGS "${OpenMP_CXX_FLAGS}")

作为旁注,如果你真的用 C 而不是 C++ 编程,你不需要 CXX_FLAGS 你可以只使用 C_FLAGS

在现代 CMake 中,您应该使用 OpenMP's imported targets

cmake_minimum_required(VERSION 3.14)
project(Parallelexamples LANGUAGES C)

find_project(OpenMP REQUIRED)

add_executable(Parallelexamples main.c)
target_link_libraries(Parallelexamples PRIVATE OpenMP::OpenMP_C)