简体   繁体   English

阅读Fortran的C ++“Hello World”

[英]Read C++ 'Hello World' from Fortran

I'm trying to verify aa 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. 我正在尝试验证一个简单的hello world函数用c ++编写的函数可以从FORTRAN脚本中调用(gfortran 4.9.20。我对c ++和FORTRAN都没什么经验,所以我认为这是我应该开始的。

//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 我可以使用下面的简单代码在c ++中调用我的hello函数

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

extern "C"
  {
    void worker();
  }

I thought all was well until I attempted to read the same code using FORTRAN. 我认为一切都很顺利,直到我尝试使用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 以下是我的FORTRAN代码

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. 我在'code.h'标题中得到8个错误。 Although my c++ code can read the header FORTRAN can not. 虽然我的c ++代码可以读取标题FORTRAN不能。 All my internet research so far has lead me here in hopes someone with experience could help me out. 到目前为止,我所有的互联网研究都引导我到这里,希望有经验的人可以帮助我。

Thanks 谢谢

You cannot include a C++ header in Fortran. 您不能在Fortran中包含C ++标头。 You must create an interface block which describes the procedure so Fortran can call it: 您必须创建一个描述该过程的接口块 ,以便Fortran可以调用它:

  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. 您可能仍然遇到问题,不建议将Fortran和C ++ I / O( std:cout流和print语句)合并到一个可执行文件中。 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). 忘了FORTRAN 77,它已经40岁了,这比这里的很多人(包括我)都要多。 Even Fortran 90 is too old considering how quickly computers and programs evolve. 考虑到计算机和程序的发展速度,即使Fortran 90也太老了。 The latest standard is Fortran 2008 and Fortran 2015 exists as a draft. 最新标准是Fortran 2008,Fortran 2015作为草案存在。

See questions and answers in for much more about interfacing C and C++ with Fortran. 有关将C和C ++与Fortran连接的更多信息,请参阅问题和解答。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM