Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
28441 Discussions

Linking Fortran I/O code compiled by ifort on WSL2 to g++

Beliavsky
Beginner
495 Views

I can link the Fortran code

module m
use iso_c_binding, only: c_float, c_int
implicit none
contains
subroutine print_stats(n,x) bind(c)
integer(kind=c_int)  , intent(in)  :: n
real(kind=c_float)   , intent(in)  :: x(n)
if (n < 1) return
print "(a,*(1x,f0.1))","min, max, mean =",minval(x),maxval(x),sum(x)/n
end subroutine print_stats
end module m

 to the C++ code

extern "C" {
void print_stats (const int *n, const float *x);
} // prototype produced by gfortran -fc-prototypes

int main() {
   const int nx = 4;
   float x[nx] = {5.0,2.0,7.0,4.0};
   print_stats(&nx,x); // min, max, mean = 2.0 7.0 4.5
   // &nx used since argument n does not have VALUE attribute
}

on WSL2 with

gfortran -c print_stats.f90
g++ print_stats.o call_print_stats.cpp -lgfortran

The -lgfortran is needed because the Fortran code does I/O. Trying ifort with

ifort -c print_stats.f90
g++ print_stats.o call_print_stats.cpp

I get

/usr/bin/ld: print_stats.o: relocation R_X86_64_32 against `.rodata' can not be used when making a PIE object; recompile with -fPIE
collect2: error: ld returned 1 exit status

and trying with the suggested option

ifort -c -fPIE print_stats.f90
g++ print_stats.o call_print_stats.cpp

 gives

/usr/bin/ld: print_stats.o: in function `print_stats':
print_stats.f90:(.text+0x68): undefined reference to `for_write_seq_fmt'
/usr/bin/ld: print_stats.f90:(.text+0x15a): undefined reference to `for_write_seq_fmt_xmit'
/usr/bin/ld: print_stats.f90:(.text+0x24c): undefined reference to `for_write_seq_fmt_xmit'
/usr/bin/ld: print_stats.f90:(.text+0x326): undefined reference to `for_write_seq_fmt_xmit'
collect2: error: ld returned 1 exit status

On WSL2, how can I link a C++ program compiled with g++ to Fortran code compiled with ifort that does I/O?

0 Kudos
1 Solution
Ron_Green
Moderator
489 Views

try ifort for the final link with -nofor-main

 

ifort -c -fPIE print_stats.f90
g++ -c call_print_stats_cpp.cpp
ifort -nofor-main -o printit.exe call_print_stats.o print_stats.o 

 

I have no idea if this will work.  Might try -static also

View solution in original post

0 Kudos
1 Reply
Ron_Green
Moderator
490 Views

try ifort for the final link with -nofor-main

 

ifort -c -fPIE print_stats.f90
g++ -c call_print_stats_cpp.cpp
ifort -nofor-main -o printit.exe call_print_stats.o print_stats.o 

 

I have no idea if this will work.  Might try -static also

0 Kudos
Reply