Search code examples
c++linkergmp

Linking error in GMP when trying to generate prime numbers in C++


I'm trying to write a simple program that generates big prime numbers in GMP as part of a bigger project, so far I've sketched out the following function:

primes.cpp

#include"primes.h"

void random_prime(mpz_t result){ 
    gmp_randstate_t state;
    mpz_t prime;

    mpz_init(prime); 
    gmp_randinit_default(state);

    mpz_set(result,prime); 
    mpz_clear(prime); 
    gmp_randclear(state);
}

primes.h

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

using namespace std;

void random_prime(mpz_t resultado);

This gets compiled as such

CC = g++

all: link

primes:
    ${CC} -c primes.cpp -lgmpxx -lgmp

main: primes ...
    ${CC} -Wall main.cpp -c -lgmpxx -lgmp

link: main
    ${CC} -o main primes.o ...

I get these errors just after the "link" line is run:

primes.o: In function `random_prime(__mpz_struct*)':
primes.cpp:(.text+0x23): undefined reference to `__gmpz_init'
primes.cpp:(.text+0x2f): undefined reference to `__gmp_randinit_default'
primes.cpp:(.text+0x42): undefined reference to `__gmpz_set'
primes.cpp:(.text+0x4e): undefined reference to `__gmpz_clear'
primes.cpp:(.text+0x5a): undefined reference to `__gmp_randclear'

I've read the manual a few times now, to no avail, I also found some related questions on SO and other forums, but none helped. At last I tried reinstalling the library, twice, and that also has not helped.

Any help would be very appreciated.


Solution

  • The -l option is used when linking, and not compiling the individual .cpp files.

    link: main
        ${CC} -o main primes.o ...  -lgmpxx -lgmp
    

    And get rid of the -l option everywhere else.