Read C++ 'Hello World' from Fortran

二次信任 提交于 2019-12-10 10:25:11

问题


I'm trying to verify a a simple hello world function written in c++ can be called from a FORTRAN script (gfortran 4.9.20. I have little experience with both c++ and FORTRAN so I thought this is were I should start.

//code.cpp
#include <iostream>

extern "C"
{
  void worker();
  int main()
    {
      worker();
    }
  void worker()
    {
      std::cout << "Hello, World!\n";
    }
}

and a header as follows

//code.h
#include "code.cpp"

extern "C"
  {
    void worker();
  }

I was able to call my hello function in c++ with the simple code below

//readheader.cpp
#include "code.h"

extern "C"
  {
    void worker();
  }

I thought all was well until I attempted to read the same code using FORTRAN. It could be my compile line and at this point I'm not sure which part of my code is broken. Below is my FORTRAN Code

c codeF.f

      program main
      include 'code.h'
      print *, 'Calling C'
      call worker()
      print *, 'Back to F77'

      end program main

my compile script

gfortran -I/Path/to/file -c codeF.f

where I get about 8 errors with the 'code.h' header. Although my c++ code can read the header FORTRAN can not. All my internet research so far has lead me here in hopes someone with experience could help me out.

Thanks


回答1:


You cannot include a C++ header in Fortran. You must create an interface block which describes the procedure so Fortran can call it:

  program main

    interface
      subroutine worker() bind(C,name="worker")
      end subroutine
    end interface

    print *, 'Calling C'
    call worker()
    print *, 'Back to F2003'

  end program main

You may still have problems, it is not advisable to combine Fortran and C++ I/O (the std:cout stream and the print statement) in one executable. They are not guaranteed to be compatible and weird things can happen.

And forget FORTRAN 77, it is 40 years old, that is more than many people here (including me). Even Fortran 90 is too old considering how quickly computers and programs evolve. The latest standard is Fortran 2008 and Fortran 2015 exists as a draft.

See questions and answers in fortran-iso-c-binding for much more about interfacing C and C++ with Fortran.



来源:https://stackoverflow.com/questions/36463225/read-c-hello-world-from-fortran

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!