【问题标题】:Error " undefined reference to `std::ios_base" while linking cpp header only library to fortran [duplicate]将 cpp 仅标头库链接到 fortran 时出现错误“未定义对`std::ios_base 的引用”[重复]
【发布时间】:2020-01-06 12:28:20
【问题描述】:

我正在尝试将仅标头库(在 cpp 中)链接到 fortran 代码。我正在使用this example 来测试我的库。

   $ 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

为了编译我正在使用:

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

如果我删除我的库头,这运行正常。但是包含时出现此错误:

    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

我可能做错了什么?

【问题讨论】:

  • mylib.hpp的内容是什么?您可能包括 iostream 或类似名称。
  • 为什么是#include&lt;cmath&gt;?为什么#include&lt;mylib/mylib.hpp&gt;
  • 似乎链接器正在链接 libc 而不是 libstdc++,换句话说,您需要以某种方式以 C++ 模式链接。
  • -lc 是做什么的?
  • @rveerd 是的。 mylib 包含类似于 std::cout 的函数来打印变量。

标签: c++ linker linker-errors gfortran


【解决方案1】:

您没有链接 C++ 标准库:

gfortran -lc -lstdc++ -o fprogram fprogram.o cppfunction.o
//           ^^^^^^^^

【讨论】:

  • 谢谢。我在用 g++ 编译 .C 文件时使用它。
  • @Evg 是的。我在使用 g++ 编译时使用了 -lstdc++。上述答案中的完整命令有所帮助。
  • -lstdc++ 应该在目标文件之后(至少,在 C++ 之后),而不是在它们之前。否则,发出“未定义的引用”。
  • @AshishMagar 您的g++ 调用具有-c(仅编译),因此不涉及任何库。
猜你喜欢
  • 1970-01-01
  • 2016-12-10
  • 2012-07-07
  • 2020-03-15
  • 1970-01-01
  • 2012-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多