英文:
Error " undefined reference to `std::ios_base" while linking cpp header only library to fortran
问题
我正在尝试将一个仅包含头文件的C++库与Fortran代码连接起来。我正在使用此示例来测试我的库。
$ 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
我可能做错了什么吗?
<details>
<summary>英文:</summary>
I am trying to link a header only library (which is in cpp) to a fortran code. I am using [this example][1] 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?
[1]: https://www.cae.tntech.edu/help/programming/mixed_languages
</details>
# 答案1
**得分**: 0
你没有链接C++标准库:
gfortran -lc -lstdc++ -o fprogram fprogram.o cppfunction.o
// ^^^^^^^^
<details>
<summary>英文:</summary>
You're not linking the C++ standard library:
gfortran -lc -lstdc++ -o fprogram fprogram.o cppfunction.o
// ^^^^^^^^
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论