Search code examples
copenmpclion

Clion and OpenMP


I am learning parallel computing and have started my journey with OpenMP and C.

I have been configuring Clion, yet no luck.

#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");

}

But i am getting this error:

In function main': C:/Users/John/CLionProjects/Parallelexamples/main.c:6: undefined reference toomp_get_num_threads' C:/Users/John/CLionProjects/Parallelexamples/main.c:7: undefined reference to `omp_get_thread_num' collect2.exe: error: ld returned 1 exit status mingw32-make.exe[2]: * [Parallelexamples.exe] Error 1 CMakeFiles\Parallelexamples.dir\build.make:95: recipe for target 'Parallelexamples.exe' failed mingw32-make.exe[1]: * [CMakeFiles/Parallelexamples.dir/all] Error 2 CMakeFiles\Makefile2:66: recipe for target 'CMakeFiles/Parallelexamples.dir/all' failed Makefile:82: recipe for target 'all' failed mingw32-make.exe: *** [all] Error 2

I have followed instructions and made my CMakeListtxt files like this:

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})

Have i missed something?


Solution

  • First off, since you are using CMake, take advantage of the FindOpenMP macro: https://cmake.org/cmake/help/latest/module/FindOpenMP.html

    cmake_minimum_required(VERSION 3.8)
    project(Parallelexamples)
    

    Secondly, it appears you aren't linking to the OpenMP runtime library. Not only must you pass the openmp compilation flags, you must also pass the correct linker flag(s):

    set_target_properties(Parallelexamples LINK_FLAGS "${OpenMP_CXX_FLAGS}")
    

    And just as a sidenote, if you are really programming with C not C++, you won't need CXX_FLAGS you can just use C_FLAGS