开发者

Calling a multithreaded (openmp) c++ routine from a Fortran routine

I have a c++ routine standalone_c.cpp and a wrapper for this in fortran standalone_f.f90 which wraps standalone_c.cpp. standalone_c.cpp is multithreaded using a openmp pragma. I am able to compile both standalone_c.cpp and the wrapper standalone_f.f90. However when I开发者_JS百科 try to link these two, I get errors like undefined reference to omp_get_thread_num, undefined reference to omp_get_num_procs. Does anyone have any experience calling multithreaded c or c++ code from a fortran routine? Can anyone guess why this is happening?

I can post some pseudo code if there is enough interest.

Edit: Compiling commands:

gcc-4.3.3/bin/g++ -O -openmp $(IFLAGS) -c standalone_c.cpp 
fce/10.1.015/bin/ifort -g -O0 standalone_f.f90
fce/10.1.015/bin/ifort $(LFLAGS) standalone_c.o standalone_f.o -o standalone

IFLAGS are for some libraries that I need, LFLAGS are the linker flags for those libraries.


The -openmp flag on ifort does more than just turn on OpenMP directive processing. It also links in the proper libraries. Assuming that you have handled the underscore in the subroutine naming problem already, then if you add -openmp to the ifort link step, that will take care of the OpenMP libraries and adding -lstdc++ will handle the C++ references (like __gxx_personality_v0).

Or you can use the options provided by ifort. Simple example:

$> cat a.f90
program a
  print *, "calling C++ program"
  call b()
end program a

$> cat b.cpp
#include <omp.h>
#include <stdio.h> 

extern "C" {
void b_(void); }

void b_(void) {
  int i;

  #pragma omp parallel for
  for (i = 0; i < 10; i++)
    printf("t#: %i  i: %i\n", omp_get_thread_num(), i);

}

$> g++ -fopenmp -c -o b.o b.cpp
$> ifort -g -O0 -c -o a.o a.f90
$> ifort -openmp -cxxlib -openmp-lib compat b.o a.o
$> export OMP_NUM_THREADS=4
$> a.out
 calling C++ program
t#: 2  i: 6
t#: 2  i: 7
t#: 2  i: 8
t#: 3  i: 9
t#: 0  i: 0
t#: 0  i: 1
t#: 0  i: 2
t#: 1  i: 3
t#: 1  i: 4
t#: 1  i: 5

You have to tell ifort to use OpenMP (-openmp), be compatible with the GNU OpenMP run-time library libgomp (-openmp-lib compat), and to link using the C++ run-time libraries provided by g++ (-cxxlib).


For the GNU compilers, the command line option to enable OpenMP is -fopenmp, not -openmp as in your example.

Secondly, when using the -fopenmp option, the compiler generates calls to the GNU OpenMP support library (libgomp). As you do the final linking step with ifort and not gfortran, you need to explicitly link to that library.

Even so, there might be problems in case -fopenmp adds some setup calls to the main program. To begin with, I would check if I could get the program running using the GNU Fortran compiler (gfortran) instead of ifort. Remember to add -fopenmp to the gfortran flags even if the Fortran code doesn't use OpenMP itself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜