21

I have C++ code with OpenMP pragmas inside. I want to test this code both for multithread mode (with OpenMP) and in single thread mode (no OpenMP).

For now, to switch between modes I need to comment #pragma omp (or at least parallel).

What is the cleanest, or default, way to enable / disable OpenMP?

nbro
  • 15,395
  • 32
  • 113
  • 196
Jakub M.
  • 32,471
  • 48
  • 110
  • 179

3 Answers3

30

If you do not compile with -fopenmp option, you won't get the parallel code. You can do it with an appropiate define and makefile that generates all codes.

The OpenMP documentation says (only an example):

#ifdef _OPENMP
   #include <omp.h>
#else
   #define omp_get_thread_num() 0
#endif

See http://www.openmp.org/mp-documents/spec30.pdf (conditional compilation).

snatverk
  • 661
  • 1
  • 7
  • 11
17

Look into the compiler manual for the switch that disables OpenMP. For GCC, OpenMP is disabled by default and enabled with the -fopenmp option.

Another option would be to run the code with the OMP_NUM_THREADS environment variable set to 1, though that is not exactly the same as compiling without OpenMP in the first place.

janneb
  • 36,249
  • 2
  • 81
  • 97
  • 2
    writing code with "#pragma omp ..." and later _not_ enabling -fopenmp causes linking erros like "undefined reference to GOMP_parallel_start" – Jakub M. Oct 21 '11 at 20:49
  • 6
    I found `omp_set_num_threads(1)` the most useful (sadly, not very elegant in my opinion) – Jakub M. Nov 07 '11 at 08:58
  • For our project we have WITH_OPENMP - a boolean build time option that handles passing -fopenmp and any defines if they are needed. Id suggest this to anyone else using openmp in a project, the ability to test without openmp can be useful at times to rule it out as a cause of any bugs. – ideasman42 Jan 20 '13 at 08:06
4

The way such things are usually handled (the general case) is with #defines and #ifdef:

In your header file:

#ifndef SINGLETHREADED
#pragma omp
#endif

When you compile, add -DSINGLETHREADED to disable OpenMP:

cc  -DSINGLETHREADED <other flags go here> code.c
Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82