Windows 上的 GMP 库 - 链接错误 LNK2001 未解析的外部符号运算符<<

gmp library on windows - linking error LNK2001 unresolved external symbol operator <<

本文关键字:lt 外部 运算符 符号 GMP 上的 链接 LNK2001 错误 Windows      更新时间:2023-10-16

我使用 mingw 和 msys 从源代码安装了 gmp 库(版本 5.1.2)。

此示例程序,取自维基百科:

#include <iostream>
#include <gmp.h>
#include <gmpxx.h>
int main()
{
    mpz_class x("7612058254738945");
    mpz_class y("9263591128439081");    
    std::cout << "n    " << x << "n*n    " << y;
    std::cout << "n--------------------n" << x * y << "nn";
    return 0;
}

如果我用 mingw 编译:

g++ -Wall -pedantic -O3 -I/c/Libs/GMP/include -L/c/Libs/GMP/lib hello_gmp.cpp -o hellocpp_gmp -lgmpxx -lgmp

它编译并运行。

如果我使用 Visual Studio 2010/2012 进行编译,则会出现以下错误:

error LNK2001: unresolved external symbol "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,struct __mpz_struct const *)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@PBU__mpz_struct@@@Z)

如果我像这样修改代码:

#include <iostream>
#include <gmp.h>
#include <gmpxx.h>
int main()
{
    mpz_class x("7612058254738945");
    mpz_class y("9263591128439081");
    mpz_class z("0");
    //std::cout << "n    " << x << "n*n    " << y;
    //std::cout << "n--------------------n" << x * y << "nn";
    z = x * y;
    std::cout << "n    " << x.get_str() << "n*n    " << y.get_str();
    std::cout << "n--------------------n" << z.get_str() << "nn";
    return 0;
}

它编译并运行。

在文件 "gmpxx.h" 中,<<运算符定义如下:

2054行关于:

/ **************** I / O operators **************** /
// These Should (and will) be provided separately
template <class T, class U>
inline std :: ostream & operator <<
(std :: ostream & o, const __ gmp_expr U> & T, expr)
{
    __gmp_expr <T, T> const & temp (expr);
    return o << temp.__get_mp();
}
template <class T>
inline std :: istream & operator >> (std :: istream & i, __ gmp_expr <t & T, expr)
{
    return i >> expr.__get_mp ();
}

2880行关于:

#define __GMP_DEFINE_BINARY_FUNCTION_UI(fun, eval_fun)                 
                                                                   
template <class T, class U>                                            
inline __gmp_expr                                                      
<T, __gmp_binary_expr<__gmp_expr<T, U>, mp_bitcnt_t, eval_fun> > 
fun(const __gmp_expr<T, U> &expr, mp_bitcnt_t l)                 
{                                                                      
    return __gmp_expr<T, __gmp_binary_expr                               
    <__gmp_expr<T, U>, mp_bitcnt_t, eval_fun> >(expr, l);        
}

3080行关于:

__GMP_DEFINE_BINARY_FUNCTION_UI(operator<<, __gmp_binary_lshift)

谢谢。

与VS2012链接时缺少gmpxx库。您可能记得在 VS 库列表中包含gmp库。把gmpxx也放在那里,你会没事的。