Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ GMP Library ostream operator<< compiles but doesn't link?

Tags:

c++

linux

gmp

$ apt-cache show libgmp10
Package: libgmp10
...
Version: 2:5.0.2+dfsg-2ubuntu2

test.cpp:

#include <gmpxx.h>
#include <iostream>

using namespace std;

int main()
{
    mpz_class x = 42;

    cout << x;
}

compile:

$ g++ -c test.cpp -o test.o
$

OK

link:

$ g++ test.o -lgmp
test.o: In function `std::ostream& operator<<
    <__mpz_struct [1]>(std::ostream&,
         __gmp_expr<__mpz_struct [1],
              __mpz_struct [1]> const&)':

test.cpp:(.text._ZlsIA1_12__mpz_structERSoS2_RK10__gmp_exprIT_S4_E[_ZlsIA1_12__mpz_structERSoS2_RK10__gmp_exprIT_S4_E]+0x2a):

undefined reference to `operator<<(std::ostream&, __mpz_struct const*)'
collect2: error: ld returned 1 exit status

It can't find operator<<(ostream&, mpz_class) at link time. What gives?

like image 886
Andrew Tomazos Avatar asked Dec 15 '22 15:12

Andrew Tomazos


2 Answers

You need to link the C++ library as well as the C library:

g++ -c test.cpp -o test.o -lgmpxx -lgmp
#                         ^^^^^^^
like image 147
Kerrek SB Avatar answered Dec 29 '22 12:12

Kerrek SB


In addition to the answer from Kerrek SB I can confirm 2 things from my experiments with this:

  1. the inclusions are the same for both -lgmp and -lgmpxx because the output of g++ -M main.cpp -lgmp is the same of g++ -M main.cpp -lgmpxx
  2. g++/gcc uses different libs for this 2 flags because g++ main.cpp -Wl,-t -lgmp is different from g++ main.cpp -Wl,-t -lgmpxx and only the last one works

I have no experience with GMP but since this directories are hard-coded in the gcc configuration, at least in this Ubuntu build, you need to make the gcc output more verbose and use a lot of patience to parse all the output and maybe you will find the real reason for this.

like image 25
user1824407 Avatar answered Dec 29 '22 13:12

user1824407