Next: Debugging (ddd)
Up: Compiled Programming Languages
Previous: Types
Fortran (compiling and using Fortran code within C/C++)
- to compile fortran code and use within a C/C++ program
// prog.f:
subroutine square(n,out)
integer n
integer out
out=n*n
return
end subroutine square
//master.C:
extern "C" void square_(int *n, int *out);
void main(){
int *input;
*input =3;
int *output;
square_(input,output);
cout « *output « endl;
// returns 9
}
- compile the fortran routines: >g77 prog.f -c -ffree-form
the -ffree-form argument allows you to get away from the very picky
fixed-form Fortran requirements (sometimes this doesn't work and you
need to remove this option)
- in the C++ code, declare the fortran function with "_"
at the end of the name and pass all arguments by reference, noting
that prog.f declares them as non-pointers (if the fortran function
is named in all caps, make sure the C/C++ references to it are lower
case, otherwise you may fail to link properly
extern "C" void functionname_(args...)
// declaring the function
functionname_(args...)// using the function
- compile the C++ code: >g++ -c master.C
- link: >g++ master.o prog.o
- you may need to use -lf, -lfortran or -lg2c in the linking
Next: Debugging (ddd)
Up: Compiled Programming Languages
Previous: Types
Chris Paciorek
2006-04-02