阅读Fortran的C ++"Hello World" [英] Read C++ 'Hello World' from Fortran

查看:72
本文介绍了阅读Fortran的C ++"Hello World"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试验证可以使用FORTRAN脚本(gfortran 4.9.20)调用用c ++编写的一个简单的hello world函数.我对c ++和FORTRAN都没有经验,所以我认为这是我应该开始的事情. /p>

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";
    }
}

和标题如下

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

extern "C"
  {
    void worker();
  }

我可以使用下面的简单代码在c ++中调用hello函数

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

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

extern "C"
  {
    void worker();
  }

在尝试使用FORTRAN读取相同的代码之前,我认为一切都很好.这可能是我的编译行,此时我不确定代码的哪一部分坏了.以下是我的FORTRAN代码

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

我的编译脚本

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

在这里,'code.h'标头出现了大约8个错误.尽管我的C ++代码可以读取FORTRAN头,但无法读取.到目前为止,我所有的互联网研究都引导我来到这里,希望有经验的人可以帮助我.

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.

谢谢

推荐答案

您不能在Fortran中包含C ++标头.您必须创建一个接口块来描述该过程,以便Fortran可以调用它:

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

您仍然可能有问题,建议不要在一个可执行文件中结合使用Fortran和C ++ I/O(std:cout流和print语句).不能保证它们兼容,并且可能会发生奇怪的事情.

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.

忘记FORTRAN 77,它已经40岁了,比这里的很多人(包括我)还多.考虑到计算机和程序的发展速度,甚至Fortran 90都太老了.最新标准是Fortran 2008,Fortran 2015作为草案存在.

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.

,以获取有关将C和C ++与Fortran接口的更多信息.

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

这篇关于阅读Fortran的C ++"Hello World"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆