undefined reference to `__imp___gmpz_init', building GMP program on Cygwin

sciencectn picture sciencectn · Mar 14, 2015 · Viewed 13.9k times · Source

I'm trying to compile this simple GMP program on Cygwin:

#include <gmp.h>

int main(){
    mpz_t i;
    mpz_init(i);
}

This is the command: gcc -lgmp test.c

I get this error:

/tmp/ccJpGa7K.o:test.c:(.text+0x17): undefined reference to `__imp___gmpz_init'
/tmp/ccJpGa7K.o:test.c:(.text+0x17): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `__imp___gmpz_init'
collect2: error: ld returned 1 exit status

Any idea what's wrong? I know it can find the library (libgmp.dll.a), but it doesn't seem to find the function.

Output of nm /usr/lib/libgmp.dll.a | grep mpz_init:

0000000000000000 T __gmpz_inits
0000000000000000 I __imp___gmpz_inits
0000000000000000 T __gmpz_init_set_ui
0000000000000000 I __imp___gmpz_init_set_ui
0000000000000000 T __gmpz_init_set_str
0000000000000000 I __imp___gmpz_init_set_str
0000000000000000 T __gmpz_init_set_si
0000000000000000 I __imp___gmpz_init_set_si
0000000000000000 T __gmpz_init_set_d
0000000000000000 I __imp___gmpz_init_set_d
0000000000000000 T __gmpz_init_set
0000000000000000 I __imp___gmpz_init_set
0000000000000000 T __gmpz_init2
0000000000000000 I __imp___gmpz_init2
0000000000000000 T __gmpz_init
0000000000000000 I __imp___gmpz_init

I tried it without grep and every single symbol in there has address 0 for some reason.

Answer

sciencectn picture sciencectn · Mar 14, 2015

This fixed it: gcc test.c -lgmp. I just put -lgmp last. This seems to be something particular to Cygwin, I tried it with both Clang and gcc-4.9 on OS X and they don't care about the order.

As for the strange behavior with the dll.a file, this is because some *.a files are just stubs that cause linking against the actual cyg*.dll which are all in /usr/bin or /usr/local/bin. However, I think this should always be automatic because Cygwin tries to be POSIX, so if you do it right then you shouldn't have to reference cyg*.dll files.

Found out from here: https://cygwin.com/ml/cygwin/2011-12/msg00305.html