0

The Problem

I am learning C and I ran into a problem where I have to find the remainder of two double numbers. But when compiling, the compiler is throwing an error. The following code was from this site. I didn't make any changes to it, just copied it and pasted it in a file called floatMod.c and compiled the file with gcc floatMod.c and it didn't get compiled and I got an error. Since I heard that -ansi with compiler command will compile it with legacy version of C, I even tried this gcc -ansi floatMod.c, cc floadMod.c and cc -ansi floadMod.c. None of these commands worked and I got the same1 error on each of these commands.

The code

/* Example using fmod by TechOnTheNet.com */

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

int main(int argc, const char * argv[])
{
    /* Define temporary variables */
    double value1, value2;
    double result;

    /* Assign the values we will find the fmod of */
    value1 = 1.6;
    value2 = 1.2;

    /* Calculate the remainder of value1 / value2 */
    result = fmod(value1, value2);

    /* Display the result of the calculation */
    printf("The fmod of %f and %f is %f\n", value1, value2, result);

    return 0;
}

The error

/usr/bin/ld: /tmp/ccb72toe.o: in function `main':
floatMod.c:(.text+0x40): undefined reference to `fmod'
collect2: error: ld returned 1 exit status

same1: In the error's first line, /tmp/ccb72toe.o: in function `main':, it is just /tmp/blahblah.o, where the blahblah part is random each time the file is compiled.

The Machine

OS: Ubuntu 20.04.2.0 LTS Desktop
Linux Kernel Version: 5.8.0-59-generic
GCC Version: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0

Sarvesh M.D
  • 192
  • 1
  • 11
  • 1
    Do you have `-lm` to link the math library in your compile command? – Retired Ninja Aug 15 '21 at 14:45
  • 1
    Does this: https://stackoverflow.com/questions/3209721/gcc-gives-error-while-using-fmod answer your question? – y_159 Aug 15 '21 at 14:47
  • @y_159 Yeah, it does. Thanks a lot. – Sarvesh M.D Aug 15 '21 at 15:38
  • 1
    Note that that is a linker error, not a compiler error. Understanding that makes the issue a build issue, not a code issue. In GCC you have to explicitly link the math library (libm) is it is separate form the rest of the standard library (libc). – Clifford Aug 15 '21 at 16:12

0 Answers0