MPFR:未定义的引用 |安装不正确?

问题描述

我正在尝试在 Ubuntu 20.04 上使用 mpfr 库。

我已经安装了它:

sudo apt-get install -y libmpfr-dev libmpfr6

我有一个简单的测试代码(从某处的教程复制):

#include <iostream>
#include <mpfr.h>

int main() {
    mpfr_t s,t;
    mpfr_init2(s,2000);
    mpfr_set_d(s,22,MPFR_RNDD);
    mpfr_init2(t,2000);
    mpfr_set_d(t,7,MPFR_RNDD);
    mpfr_div(s,s,t,MPFR_RNDD);
    mpfr_out_str(stdout,10,MPFR_RNDD);
    std::cout << std::endl;
    mpfr_clear(s);
    mpfr_clear(t);
    mpfr_free_cache();
}

它看起来像 C 代码,但这只是一个玩具示例。在实际程序中,它将是一个 C++ 代码,因此我使用 cpp 扩展和 g++ 编译器。

我编译它:

g++ -O0 -Wall --std=c++14 -L/usr/lib -lmpfr -lgmp -o test test.cpp

我收到错误,好像库定义文件丢失了...

/usr/bin/ld: /tmp/cc1XbFhH.o: in function `main':
test.cpp:(.text+0x28): undefined reference to `mpfr_init2'
/usr/bin/ld: test.cpp:(.text+0x45): undefined reference to `mpfr_set_d'
/usr/bin/ld: test.cpp:(.text+0x56): undefined reference to `mpfr_init2'
/usr/bin/ld: test.cpp:(.text+0x73): undefined reference to `mpfr_set_d'
/usr/bin/ld: test.cpp:(.text+0x8c): undefined reference to `mpfr_div'
/usr/bin/ld: test.cpp:(.text+0xb2): undefined reference to `__gmpfr_out_str'
/usr/bin/ld: test.cpp:(.text+0xd4): undefined reference to `mpfr_clear'
/usr/bin/ld: test.cpp:(.text+0xe0): undefined reference to `mpfr_clear'
/usr/bin/ld: test.cpp:(.text+0xe5): undefined reference to `mpfr_free_cache'
collect2: error: ld returned 1 exit status

我做错了什么吗?我知道图书馆那里:

$ dpkg -L libmpfr6
/.
/usr
/usr/lib
/usr/lib/x86_64-linux-gnu
/usr/lib/x86_64-linux-gnu/libmpfr.so.6.0.2
/usr/share
/usr/share/doc
/usr/share/doc/libmpfr6
/usr/share/doc/libmpfr6/AUTHORS
/usr/share/doc/libmpfr6/BUGS
/usr/share/doc/libmpfr6/NEWS.gz
/usr/share/doc/libmpfr6/README
/usr/share/doc/libmpfr6/TODO.gz
/usr/share/doc/libmpfr6/changelog.Debian.gz
/usr/share/doc/libmpfr6/copyright
/usr/lib/x86_64-linux-gnu/libmpfr.so.6
$ dpkg -L libmpfr-dev
/.
/usr
/usr/include
/usr/include/mpf2mpfr.h
/usr/include/mpfr.h
/usr/lib
/usr/lib/x86_64-linux-gnu
/usr/lib/x86_64-linux-gnu/libmpfr.a
/usr/lib/x86_64-linux-gnu/pkgconfig
/usr/lib/x86_64-linux-gnu/pkgconfig/mpfr.pc
/usr/share
/usr/share/doc
/usr/share/doc/libmpfr-dev
/usr/share/doc/libmpfr-dev/copyright
/usr/lib/x86_64-linux-gnu/libmpfr.so
/usr/share/doc/libmpfr-dev/AUTHORS
/usr/share/doc/libmpfr-dev/BUGS
/usr/share/doc/libmpfr-dev/NEWS.gz
/usr/share/doc/libmpfr-dev/README
/usr/share/doc/libmpfr-dev/TODO.gz
/usr/share/doc/libmpfr-dev/changelog.Debian.gz
/usr/share/doc/libmpfr-dev/changelog.gz

解决方法

问题出在编译命令行上。参数的顺序很重要:依赖于他人的事物必须他们所依赖的事物之前。所以如果你使用这个命令

g++ -O0 -Wall --std=c++14 -L/usr/lib -o asd asd.cpp -lmpfr -lgmp

编译会成功,因为这些库需要它们的源代码之后。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...