-1

I am trying to link a header only library (which is in cpp) to a fortran code. I am using this example to test my library.

   $ cat cppfunction.C
   #include<cmath>
   #include<mylib/mylib.hpp>

   extern "C" 
   {
        void cppfunction_(float *a, float *b);
   }
   void cppfunction_(float *a, float *b)
   {
        *a=7.0;
        *b=9.0;
   }

  $ cat fprogram.f

   program fprogram

   real a,b
   a=1.0
   b=2.0

   print*,"Before fortran function is called"
   print*,'a=',a
   print*,'b=',b

   call cppfunction(a,b)
   print*,"After cpp function is called"
   print*,'a=',a
   print*,'b=',b

   stop
   end

For compiling I am using:

    $ gfortran -c fprogram.f
    $ g++ -c cppfunction.C
    $ gfortran -lc -o fprogram fprogram.o cppfunction.o

This runs fine if I remove my library header. But have this error when included:

    cppfunction.o: In function `__static_initialization_and_destruction_0(int, int)':
    cppfunction.C:(.text+0xa1): undefined reference to `std::ios_base::Init::Init()'
    cppfunction.C:(.text+0xb0): undefined reference to `std::ios_base::Init::~Init()'
    collect2: error: ld returned 1 exit status

Anything I might be doing wrong?

8
  • What is the content of mylib.hpp? You are probably including iostream or similar. Commented Jan 6, 2020 at 12:37
  • Why #include<cmath>? Why #include<mylib/mylib.hpp>? Commented Jan 6, 2020 at 12:41
  • It seems the linker is linking with libc instead of libstdc++, in other words you need to link in C++ mode somehow. Commented Jan 6, 2020 at 12:41
  • What does -lc do? Commented Jan 6, 2020 at 12:42
  • @rveerd Yes. mylib contains function similar to std::cout to print variables. Commented Jan 6, 2020 at 12:43

1 Answer 1

0

You're not linking the C++ standard library:

gfortran -lc -lstdc++ -o fprogram fprogram.o cppfunction.o
//           ^^^^^^^^
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. I was using this while compiling the .C file with g++.
@Evg Yes. I was using -lstdc++ while compiling with g++. The complete command in above answer helped.
-lstdc++ should come after object files (at least, after C++ one), not before them. Otherwise, "undefined reference" is issued.
@AshishMagar Your g++ invocation has -c (compile-only) so does not involve any libraries.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.