我正在学习并行计算,并开始了我的 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 to
omp_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 uild.make:95:目标“Parallelexamples.exe”的配方失败
mingw32-make.exe[1]: * [CMakeFiles/Parallelexamples.dir/all] 错误 2
CMakeFiles\Makefile2:66:目标“CMakeFiles/Parallelexamples.dir/all”的配方失败
Makefile:82: 目标“全部”的配方失败
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 的导入目标。
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)