public typedefs for gmp malloc/free types

Marc Glisse marc.glisse at
Tue Aug 2 20:58:02 CEST 2011

On Tue, 2 Aug 2011, Torbjorn Granlund wrote:

> Marc Glisse <marc.glisse at> writes:
>  the following is a common use of gmp:
>        void (*gmp_free) (void *, size_t);
>        mp_get_memory_functions (NULL, NULL, &gmp_free);
>        (*gmp_free) (str, strlen (str) + 1);
>  which is valid in C, compiles with g++, but is invalid in C++
>  proper. For this reason, we have in gmpxx.h:
> What is invalid about it, in "proper C++"?

gmp_free is declared as void(*)(void*,size_t) with C++ linkage whereas 
mp_get_memory_functions takes as argument a void(*)(void*,size_t) with 
extern "C" linkage, which are 2 different types. C++ is allowed to use a 
completely different calling convention than C and there are rules 
ensuring that you can use both types of functions in your programs (you 
can even overload on linkage, and the standard C function qsort has 2 
overloads so you can pass it either a C or C++ function).

Note that since extern "C" can't appear in the middle of a function, a 
typedef is the only way to declare a local variable that is a pointer to a 
C function.

The bug in gcc:

>  extern "C" {
>    typedef void (*__gmp_freefunc_t) (void *, size_t);
>  }
>  so we can declare:
>        __gmp_freefunc_t gmp_free;
>  Now, I have to introduce this same fix in CGAL and in GCC. I believe
>  it would be good if gmp provided an official, documented typedef for
>  the types of the malloc/realloc/free functions it uses.
>  Possibly gmp_malloc_t/gmp_realloc_t/gmp_free_t, but I really don't
>  care about the name.
> Their types is defined, without a typedef in the manual:
> Please explain how new types for these function would improve things.

People would hopefully use the typedef, it would work just as well in C 
and with g++ as the explicit types, and by magic it would also work with 
correct C++ compilers, without the user needing to know about linkage 
subtleties and introducing their own typedef.

(I could add a paragraph to the manual about this issue, but I fear it 
would mostly confuse users who don't really care)

> (There is a slight backward compatibility concern wrt adding types; old
> GMP will not work as new ones.)

Anyway most projects need to work with older versions of gmp so they 
couldn't use it before several years.

Having to write the same typedef for a not-so-well-known issue in gmpxx, 
CGAL and gcc made me think something could be improved.

Now I can understand if you are reluctant to introduce these typedefs, 
since as far as I know the only compiler that currently implements linkage 
properly is sunpro...

Marc Glisse

More information about the gmp-discuss mailing list