1

So here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main()
{
        float f = .55;
        int i;
        i = round(f);
}

The first problem I am having is the round() function itself. When calling it like this: round(foo) There are no compile errors. Of coarse, this is useless as the desired output of round() is returned. But when I try to capture the output of round() like this:

i = round(f)

I get a compile time error:

test.c:(.text+0x1b): undefined reference to `round'

It is as though just trying to assign the return value of round() is forcing round() to not be defined. I have read some posts on here that said I should pass -lm to GCC, but this makes no difference.

Trying to call round() from printf gives me the same error such as:

printf("....", round(f))

This is literally driving me mad at the moment because all online references say:

int i = round(f)

Should work.

This is the latest GCC on Ubuntu 18.04.

  • What you have found about including math library is correct. You need to add that library explicitely. What is the exact command line you use with GCC? – Gerhardh Feb 17 '19 at 22:36
  • It is undefined unless you add math library. When you do not use the return value the compiler knows that `round` does not have any side effect and might optimize the complete call. If you use it (in an assignment or as parameter to another function) it cannot optimize it away causing your error. – Gerhardh Feb 17 '19 at 22:37
  • 3
    You must link `libm` to your program. For GCC put the `-lm` **at the end** of command line. – trafalgarx Feb 17 '19 at 22:41
  • I have tried the -lm. – Dean Rantala Feb 18 '19 at 00:01
  • And... I have already added the include to math.h. – Dean Rantala Feb 18 '19 at 00:01
  • Also note: GCC is NOT complaining when I have a single line like this: round(f). It ONLY complains that the function is not defined when trying to do: i=round(f). – Dean Rantala Feb 18 '19 at 00:03
  • 1
    Since you don't do anything with the result of calling `round()` — certainly when you do `round(f)` rather than `i = round(f)`, the compiler concludes it can omit the call as doing so doesn't change the computation. You might find [Linking with `gcc` and `-lm` doesn't define `ceil()` on Ubuntu](https://stackoverflow.com/questions/8266183/linking-with-gcc-and-lm-doesnt-define-ceil-on-ubuntu/) has some use, too. Note that if you use `round(3.2)` or similar, the compiler can calculate the result at compile time and avoid needing to link the `round()` function too. – Jonathan Leffler Feb 18 '19 at 01:44

1 Answers1

0

Okay all... so - this was certainly my own ignorance. I was obviously not adding the " -lm" to the END of the argument list. All is working now.