2

is it possible to call a C++ function from FORTRAN such as

#include <iostream.h>
extern "C"
{
    void single_cell(void)
    {
        cout<<"Hi from C++";
    }
}

So when I am using C it is working fine but with the C++ function it gives errors like Undefined error to cout etc

phoxis
  • 60,131
  • 14
  • 81
  • 117
Zahur
  • 101
  • 1
  • 3
  • 9
  • You would need `using namespace std;` or `std::cout` but i dont think this will work in an `extern "C"` –  Aug 31 '11 at 10:11
  • 1
    I'a not sure but maybe you must `include` and use `std::cout`, but I don't know it will be working – nirmus Aug 31 '11 at 10:12
  • You will need to edit the question to explain which C++ and fortran compilers you are using and how you are doing the linking before anyone can give you a definitive answer. – talonmies Aug 31 '11 at 11:12

2 Answers2

3

Both g++ and gfortran, used as linkers, bring in extra libraries. That is why the Fortran/C++ combination is trickier than the Fortran/C combination ... just using the correct compiler as the linker won't work, you need to add a libary. Already suggested is to link with gfortran and specify the C++ runtime libraries. You can also link with g++ and specify the Fortran runtime libraries. See Linking fortran and c++ binaries using gcc for the details of both approaches.

Community
  • 1
  • 1
M. S. B.
  • 28,968
  • 2
  • 46
  • 73
  • g++ main.o print_hi.o -o main -lgfortran after using this command it gives the error as /cygnus/cygwin-b20/H-i586-cygwin32/i586-cygwin32/bin/1d cannot open -lgfortran: no such a file or director what is the exact procedure to include the path because i think the gfortran is installed in some other directory – Zahur Aug 31 '11 at 15:10
1

Assuming you could have your Fortran code call into a C function, the problem is not the code but rather how you are linking. When you're linking C++ objects you need to also pull in the C++ runtime. If using GCC, link with the g++ command and it will pull in the parts you need.

mah
  • 39,056
  • 9
  • 76
  • 93
  • 1
    Linking with g++ (and doing nothing else) will just result in the fortran runtime libraries not being found. The solution is either to link with the fortran compiler and add the C++ runtime libraries to the link statement, or link with the C++ compiler and add the fortran runtime libraries to the link statement. Both will work. – talonmies Aug 31 '11 at 10:21
  • @ talonmies yes you are right. The prblem is in the linking phase and i am uisng the gfortran commands so it is gives problem with the C++ cout. can you please give detail how i include the libraries in the linking command – Zahur Aug 31 '11 at 10:32
  • I am using Iso_c_binding in fortran for calling this C++ funciton, which works fine in the case of C but not in the C++ – Zahur Aug 31 '11 at 10:39