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

3
  • You would need using namespace std; or std::cout but i dont think this will work in an extern "C" Commented Aug 31, 2011 at 10:11
  • 1
    I'a not sure but maybe you must include<iostream> and use std::cout, but I don't know it will be working Commented Aug 31, 2011 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. Commented Aug 31, 2011 at 11:12

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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
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.

3 Comments

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 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
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++

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.