Disable OpenMP

I’m using CMake v3.19.3 on Ubuntu 18.04.5 with clang 11.0.1 and VS Code. Here is my CMakeLists.txt file:

cmake_minimum_required(VERSION 3.18)
project(ocv VERSION 0.1.0)

find_package(fmt REQUIRED)
find_package(OpenCV 4.5 REQUIRED)
find_package(OpenMP REQUIRED)

add_executable(ocv main.cpp grid.cpp)

include_directories(
  /home/paul/include
  /home/paul/eigen-3.3.9
  /home/paul/eigen-3.3.9/unsupported
  /home/paul/Open3D/3rdparty/tinyfiledialogs/include
  /home/paul/boost_1_75_0
)

target_precompile_headers(ocv PRIVATE ocv.hpp)

target_compile_options(ocv PRIVATE -O3 -fopenmp  -Wno-narrowing)
# target_compile_options(ocv PRIVATE -O3 -fno-openmp -Wno-narrowing)

target_link_libraries(ocv 
  fmt::fmt
  ${OpenCV_LIBS}
  OpenMP::OpenMP_CXX
)

set(CMAKE_VERBOSE_MAKEFILE TRUE)
set_property(TARGET ocv PROPERTY RULE_LAUNCH_COMPILE "${CMAKE_COMMAND} -E time")
set_property(TARGET ocv PROPERTY CXX_STANDARD 20)

Regardless which of the two target_compile_options lines above I choose, the target is compiled with OpenMP code generated. What is the correct way to turn OpenMP on and off.

Have you tried removing OpenMP::OpenMP_CXX from the target_link_libraries call?

1 Like

Yes, I tried. It produces linker error:

[build] /usr/bin/ld: CMakeFiles/ocv.dir/grid.cpp.o: undefined reference to symbol 'omp_get_thread_num@@OMP_1.0'
[build] //usr/lib/x86_64-linux-gnu/libgomp.so.1: error adding symbols: DSO missing from command line

when used with -fopenmp. Works fine with -fno-openmp, but I would rather have a less drastic solution for switching between serial and parallel versions of the project. Is there a single compiler switch, or CMake variable, which can do the job?

I think using/not using OpenMP::OpenMP_CXX should be enough. It comes with the -fopenmp flag attached to its use already, so you shouldn’t need to do anything with the flag (additionally, its spelling can change based on the compiler in use; the target already accounts for that).

1 Like

Thank you. It does work. I wonder though, if this will hold for more complicated OpenMP flags like device offload, e.g. –fopenmp-targets=nvptx64-nvidia-cuda. I will test it when I get to that stage.

Hmm. I don’t think so. It’s something that could be added to FindOpenMP though (either as a target or a function to make the flags based on other information). Please open an issue to track such an enhancement as openmp-targets currently doesn’t appear anywhere in CMake’s codebase.

Cc: @robert.maynard

1 Like

Done.

Thanks. For reference: https://gitlab.kitware.com/cmake/cmake/-/issues/21784