Sunday, October 10, 2010

gmp library - including methods in your c code

.
The gnu Gmp library has many methods for dealing with huge integers.
( It does a lot more than that but I keep a narrow focus for this article )


Here are some links to the documentation for versions 5 and older version 4

When writing your own programs in C, that make use of gmp, you will use an include such as:

#include <gmp.h>

...and then perhaps if working with mpz Integers you might use some of the Integer functions of gmp.

Diving in and compiling with gcc, you might see 'undefined reference to ...' messages, until you have the gmp headers installed, and tell gcc about that.


Compiling against the gmp library is different than simply using the gmp library, and you may need an additional package installed.

On Debian and Ubuntu the source files and/or headers are kept in separate packages from the executables, so as not to bloat your system.

Install the source for gmp using the following command:

apt-get install libgmp-dev

(*Older Debian 6 Squeeze package is named libgmp3-dev rather than libgmp-dev)

...which brings down the necessary files so that gcc can use them in it's compile.


I used aptitude rather than apt-get in the above but the result is the same.

Recap:
  • Use in your C program #include <gmp.h>
  • Have the dev package installed on your system
  • Use the -lgmp flag when you invoke gcc
  • gcc arguments -lm and -lgmp should be the LAST argument
      [ as shown in the first screenshot ]

Note: I use GNU/Linux and give my instructions for Debian and similar systems. If you use a different platform, then I am unable to help with that and you should look elsewhere for instructions tailored to your chosen platform.


(optional) Integer functions of gmp:

What follows are some hints/personal notes, which serve as a useful reminder to me personally.

( Please consult the official manual, using the links in the first paragraph, as a definitive source of explanation. )


/* mpz_sub_ui versus mpz_sub where ui indicates unsigned integer rather than mpz processing */

/* mpz_cdiv_q versus mpz_tdiv_q will ceiling rather than truncate when calculating quotient */

/* mpz_cmp_ui Compare op1 and op2. Return a positive value if op1 > op2, zero if op1 = op2, or a negative value if op1 < op2. */
.

1 comment:

  1. From experience it only takes me a month or so away from C to start feeling rusty.

    Here are some places that give me a quick refresher in the main constructs:
    Pleac code comparison - section for C
    Giorgio Ingargiola pages at Temple University, Philadelphia

    ReplyDelete