c++ program using GMP library

Badshah picture Badshah · Jan 2, 2013 · Viewed 38.9k times · Source

I have installed GMP using the instruction on this website: http://www.cs.nyu.edu/exact/core/gmp/ Then I looked for an example program using the library:

    #include <iostream>
#include <gmpxx.h>
using namespace std;
int main (void) {
mpz_class a, b, c;
a = 1234;
b = "-5678";
c = a+b;
cout << "sum is " << c << "\n";
cout << "absolute value is " << abs(c) << "\n";
cin >> a;
return 0;
}

But if I compile this using the command: g++ test.cpp -o test.exe, it says gmpxx.h: no such file or directory. How can I fix this? I am kind of new to this. And I am using MinGW.

Answer

someoneigna picture someoneigna · Jan 2, 2013

Get the actual version here GNU GMP Library. Make sure you configure it to be installed in /usr/lib (pass --prefix=/usr to configure).

Here you have documentation: GNU GMP Manual.

You are not using the lib correctly. I don't know if you can directly access mpx values with C++ functions but, here you have a working example of what you wanted to achieve:

#include<iostream>
#include<gmp.h>

using namespace std;

int main (int argc, char **argv) {

    mpz_t a,b,c;
    mpz_inits(a,b,c,NULL);

    mpz_set_str(a, "1234", 10);
    mpz_set_str(b,"-5678", 10); //Decimal base

    mpz_add(c,a,b);

    cout<<"\nThe exact result is:";
    mpz_out_str(stdout, 10, c); //Stream, numerical base, var
    cout<<endl;

    mpz_abs(c, c);
    cout<<"The absolute value result is:";
    mpz_out_str(stdout, 10, c);
    cout<<endl;

    cin.get();

    return 0;
}

Compile with:

g++ -lgmp file.cpp -o file