0

I'm having trouble compiling a project requiring OpenMP using CMake and clang, I set my CMakeLists.txt like this

cmake_minimum_required(VERSION 3.20)
project(cmat C)

set(CMAKE_C_STANDARD 11)

include_directories("/usr/local/include" "/usr/local/opt/llvm/include")
link_directories("/usr/local/lib" "/usr/local/opt/llvm/lib")

add_library(cmat SHARED cmat.c Calculation/_Basic_Calculate_.c Calculation/_Basic_Calculate_.h)

And when I started to build my project, it gave error

Undefined symbols for architecture x86_64:
  "_omp_get_thread_num", referenced from:
      _NmMulMat in _Basic_Calculate_.c.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[3]: *** [libcmat.dylib] Error 1
make[2]: *** [CMakeFiles/cmat.dir/all] Error 2
make[1]: *** [CMakeFiles/cmat.dir/rule] Error 2
make: *** [cmat] Error 2

I've tried some of the other answers like this and this, but they just don't work for me.

The clang version for my Mac is 13.0.0 and CMake is of 3.21.3_1, I'm using Clion as IDE, and such command will work when compiling files by shell

clang -Xpreprocessor -fopenmp -I/usr/local/include -L/usr/local/lib -lomp filename.c -o output

Great appreciate for your help.

Sqr
  • 83
  • 6

1 Answers1

-3

You need to add -fopenmp to the linker flags as well by providing -DCMAKE_EXE_LINKER_FLAGS=-fopenmp [and any other options like -g].

In CLion (which I don't use) this would be specified in Preferences -> Build, Execution, Deployment -> CMake -> CMake options as far as I understand the documentation.

Also please note that explicitly linking with -lomp is probably the wrong strategy, that happening should be a side-effect of specifying -fopenmp.

TJahns
  • 197
  • 1
  • 9
  • Thanks for that, but it still gave error `clang: error: linker command failed with exit code 1 (use -v to see invocation)` – Sqr Oct 17 '21 at 01:27
  • My problem finally solved by adding `set(CMAKE_C_FLAGS "-std=c11 -Xpreprocessor -fopenmp -L/usr/local/lib -I/usr/local/include -lomp")` into CMakeLists.txt, though I don't know the difference between this and setting `-DCMAKE_EXE_LINKER_FLAGS` in options, thanks anyway! – Sqr Oct 17 '21 at 02:55
  • 2
    _**No!**_ Use `find_package(OpenMP REQUIRED)` and link to `OpenMP::OpenMP_C` – Alex Reinking Oct 17 '21 at 04:02
  • @AlexReinking OpenMP is intended as an optional dependency so it shouldn't be part of the build recipe itself in my opinion but rather enter the build in a deployment-specific way. – TJahns Oct 18 '21 at 07:57
  • 1
    Then you should drop `REQUIRED` and conditionally link to `OpenMP::OpenMP_C`. Monkeying around with flags for this is plain wrong. – Alex Reinking Oct 18 '21 at 19:39