I am trying to pass the array between functions of c++ and fortran. The Fortran code looks like:
PROGRAM vector_adder
IMPLICIT NONE
INTEGER,allocatable :: a(:),b(:),c(:)
INTEGER :: i, num
num = 6
allocate(a(num),b(num),c(num))
!C fill vectors with values
DO i = 1,num
a(i) = i*i
b(i) = i
END DO
CALL ADD_VECTORS(a,b,c,num)
WRITE(*,'(I5,I5,I5)') (c(i),i =1,num)
STOP
END PROGRAM
And the C++ code looks like:
#include <cmath>
#include <vector>
#include <iostream>
using namespace std;
void add_vectors__(int* a, int* b, int* c, int& num);
extern "C" void add_vectors_(int* a, int* b, int* c, int& num)
{
add_vectors__(a, b, c, num);
}
void add_vectors__(int* a, int* b, int* c, int& num)
{
for (size_t i = 0; i<num; i++)
{
c[i] = a[i] + b[i];
cout <<c[i]<<endl;
}
}
And I compile the code as:
rm -r *.o
rm -r prog
g++ -c c++Code.cpp
gfortran -c fCode.f90
gfortran -o prog fCode.o c++Code.o
./prog
If I remove the line of court in the c++ file, the code runs. But introducing the cout line gives me the following errors of undefined references as:
c++Code.o: In function `add_vectors__(int*, int*, int*, int&)':
c++Code.cpp:(.text+0xc0): undefined reference to `std::cout'
c++Code.cpp:(.text+0xc5): undefined reference to `std::ostream::operator<<(int)'
c++Code.cpp:(.text+0xcf): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)'
c++Code.cpp:(.text+0xda): undefined reference to `std::ostream::operator<<(std::ostream& (*)(std::ostream&))'
c++Code.o: In function `__static_initialization_and_destruction_0(int, int)':
c++Code.cpp:(.text+0x110): undefined reference to `std::ios_base::Init::Init()'
c++Code.cpp:(.text+0x125): undefined reference to `std::ios_base::Init::~Init()'
collect2: error: ld returned 1 exit status
./run: line 6: ./prog: No such file or directory