-1

I've just started using the GMP and MPFR. I'm writing a program in C and would like to make a function that (for example) takes as input an mpfr_t variable and returns an mpfr_t variable. I'm not sure of the definition of mpfr_t, but I tried naively doing this and get compile errors.

Any information regarding this would be much appreciated.

  • It's hard to help when you don't show us what you did or what the result was. Please [edit] your question to include a [mcve] and the result. – Toby Speight Jan 16 '23 at 17:21
  • We can guess or you can tell us what is wrong. Only one of these will get you the answers you are looking for. [Can you compile this?](https://www.mpfr.org/sample.html) – Gerhard Jan 17 '23 at 06:55

2 Answers2

1

mpfr_t is a type, and it's an opaque type, meaning you're not supposed to know its definition. You should be able to just define a function

mpfr_t f(mpfr_t x)
{
    // ...
}

as long as whatever's in the ... only performs valid operations (such as MPFR library functions) on x.

If that doesn't work, you should post the error you're getting.

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • 1
    Make sure to include the `` header, and to link against mpfr and gmp: `-lmpfr -lgmp`. – Stephen Canon Apr 20 '11 at 18:39
  • 2
    "error: 'f' declared as function returning an array". MPFR functions are called `fun(result, argument)` and write to their first argument. – Marc Glisse Feb 18 '15 at 16:56
  • 1
    `meaning you're not supposed to know its definition.` It's wrong. Functions can't return arrays. – 273K Jan 15 '23 at 18:11
0

The type is mostly opaque, but the documentation does give some useful information.

In particular, it is an array [1] of a struct type. This tell us that you don't need to call an allocation function to create one. Creating the variable creates the storage, and you can make automatic or static variables and you know where they live.

You do need to call the mpz_init() function to initialize it, but being an array type, it decays to a pointer in a function call's argument list. That means simply passing the variable (without an &) means the function can modify that storage. Thus it's (only) important to pay attention to the const declarations in the function prototypes. It's the one without the const that is the destination, in all cases.

Being an array type also means that you cannot copy an mpz_t value with a simple assignment, but rather memcpy or similar. Because you cannot copy arrays by assignment.

luser droog
  • 18,988
  • 3
  • 53
  • 105