fortranModule.f90
module fortranModule
use iso_c_binding
implicit none
contains
subroutine print_f90()
implicit none
write(*,*) "This is a message from Fortran 90."
end subroutine print_f90
end module fortranModule
fortranProgram.f90
program fortranProgram
use iso_c_binding
use fortranModule
implicit none
!Do some work as input for print_f90()
call print_f90()
end program fortranProgram
main.cpp
extern "C" {
extern void fortranProgram(void);
}
int main(void) {
fortranProgram();
return 0;
}
Attempting to compile with the following steps:
gfortran -c fortranModule.f90 fortranProgram.f90
g++ -c main.cpp
g++ main.o fortranModule.o fortraProgram.o -o main -lgfortran
gives
duplicate symbol _main in:
main.o
fortranProgram.o
ld: 1 duplicate symbol for architecture x86_64
How can I link a fortran program with module dependencies to a c++ program? Is this possible? Do I need to rewrite fortranProgram.f90 as a module or subroutine? Maybe there is a naming scheme similar to __modulename_MOD_subroutinename ?
Changing fortranProgram.f90 to
subroutine call_print_f90(num) bind(c, name='call_print_f90')
use iso_c_binding
use fortranModule
implicit none
call print_f90(num)
end subroutine call_print_f90
and changing main.cpp to
extern "C" {
extern void call_print_f90(void);
}
int main(void) {
call_print_f90();
return 0;
}
resolves the problem of having two conflicting "mains".
Below is a solution in which fortranProgram.f90 is refactored as a module.
fortranProgram.f90
module fortranProgram
use iso_c_binding
use fortranModule
implicit none
contains
subroutine call_print_f90() bind(c, name='call_print_f90')
call print_f90(num)
end subroutine call_print_f90
end module fortranProgram
main.cpp
extern "C" {
extern void call_print_f90(void);
}
int main(void) {
call_print_f90();
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.