1
votes

I am experiencing problems with displaying values on the console while invoking a C subroutine from a fortran subroutine. I have print statements immediately before and after the call to the C subroutine, as well as a print statement within the C subroutine. However, upon executing the program, the C statements are printed before the two Fortran statements, rather than between them. I’ve looked thoroughly within the code, and there are no calls to the C subroutine elsewhere, so there is no obvious reason why the c statement should be printed before the Fortran statement. I created a simpler Fortran-C program (below) to try to reproduce the problem, but the code executed the print statements in the expected order. I wonder if someone has any insights as to what could be the problem. Thank you.

Sample Fortran code:

  program test

     print *, 'Calling C program'

     call cprog()

     print *, 'Finished calling C program.'

   end program test

sample c code to be invoked from fortran:

void cprog()
{

  printf("THIS IS A TEST\n");

  return;
}

Output:

Calling C program

THIS IS A TEST

Finished calling C program.

Output similar to what I’m experiencing with more complex code:

THIS IS A TEST

Calling C program

Finished calling C program

1
Have you tried compiling with -O0 or whatever turns off optimization on your compiler? And are you actually writing to stdout? Or into a file? It makes a huge difference with hybrid code.Andras Deak
It sounds like Fortran is buffering its output. You need to flush the output buffer before calling the C program.Barmar
Flushing resolved the issue - thank you so much!Hannah
Flush will help in some cases (and yours, apparently), but IanH's solution of writing from one language is the only one I know of guaranteed to work.Ross
The supposed duplicate answer is not an answer to this question.IanH

1 Answers

4
votes

The behaviour of mixed language input or output to the same external unit (~file) is processor dependent - see F2008 15.5.1p6. Amongst other things, this is to accommodate the possibility of buffering (or outright incompatibility) in the runtime support for each language. Because the behaviour is processor dependent there is no guarantee of any particular order.

The robust solution is to do all the input/output to that particular file from the one language, perhaps by providing a procedure/function that the other language can call to do input/output.