7

The GMP docs say that static linking may provide a small performance improvement.

I am having a problem getting it to staticly link libgmp on my Linux systems. I've narrowed down the issue I'm having to a tiny test case.

gmptest.c

#include <gmp.h>

int main(int argc, char** argv) {
    mpz_t foo;
    mpz_init(foo);
    return 0;
}

Makefile:

all: clean gmptest static

clean:
    rm -f *.s
    rm -f *.o
    rm -f gmptest
    rm -f static-gmptest

gmptest: Makefile gmptest.c
    gcc -std=c99 -O3 -lgmp gmptest.c -o gmptest

static: clean Makefile gmptest.c
    gcc -std=c99 -O3 -static /usr/lib/libgmp.a gmptest.c -o static-gmptest

The non-static binary is compiled and linked without any issues, but 'Make static' produces:

gcc -std=c99 -O3 -static /usr/lib/libgmp.a gmptest.c -o static-gmptest
/tmp/ccWSFke9.o: In function `main':
gmptest.c:(.text+0x8): undefined reference to `__gmpz_init'
collect2: ld returned 1 exit status
make: *** [static] Error 1

The library does exist:

chris@vostro:~/Dropbox/static$ ls -lA /usr/lib/libgmp.a 
-rw-r--r-- 1 root root 1041666 2010-02-26 13:20 /usr/lib/libgmp.a

I have also tried -lgmp for the static linking, but the error is the same.

This is all on Ubuntu 10.04 and 10.10 AMD64.

Can some enlighten me as to the obvious error I'm making?

Thanks,

Chris.

fadedbee
  • 42,671
  • 44
  • 178
  • 308

2 Answers2

11

Try

 gcc -std=c99 -O3 -static gmptest.c -lgmp -o static-gmptest

since libraries should always be linked in the good order, and after the program or object files using them.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
0

Here, in GMP 6.1.2 / MINGW and assuming certain portability, I find that the header "gmp.h" has fix link mode, as configured with GMP build parameters.

/* Instantiated by configure. */
#if ! defined (__GMP_WITHIN_CONFIGURE)
    #define _LONG_LONG_LIMB 1
    #define __GMP_LIBGMP_DLL  0
#endif

As with this the compiler will never generate static object decorations, and so the linker will never match the static libgmp, I conditioned the define __GMP_LIBGMP_DLL

/* Added link switch GMP_STATIC */
#if ! defined (__GMP_WITHIN_CONFIGURE)
    #define _LONG_LONG_LIMB 1
    #ifndef GMP_STATIC // SGR 2021-12-30
        #define __GMP_LIBGMP_DLL  1
    #endif
#endif

Now, with defined GMP_STATIC the static libgmp.a is successfully attracted and without GMP_STATIC the dynamic libgmp.dll.a.

Sam Ginrich
  • 661
  • 6
  • 7