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

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.



Solution 1:[1]

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

Solution 2:[2]

I also had the same issue while using gmp.h with codeblocks on Windows 7. My solution 1. Install gmp from deval while installing cygwin 2. Add path the path of libgmp.a and libgmp.dll.a in your editor's linker 3. Rebuild all.

Solution 3:[3]

Using g++ main.c -o main -lgmp worked for me. Basically, all I had to do was putting the -lgmp in the end.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sciencectn
Solution 2 Deepak Ingole
Solution 3 datway skrt