143

Possible Duplicate:
Problem using pow() in C
what is 'undefined reference to `pow''

I'm having a bit of an issue with a simple piece of coursework for uni that's really puzzling me.

Essentially, I've to write a program that, amongst other things, calculates the volume of a sphere from a given radius. I thought I'd use the pow() function rather than simply using r*r*r, for extra Brownie points, but the compiler keeps giving me the following error:

undefined reference to 'pow' collect2: error: ld returned 1 exit status

My code looks like the following:

#include <math.h>

#define PI 3.14159265 //defines the value of PI

/* Declare the functions */
double volumeFromRadius(double radius);

/* Calculate the volume of a sphere from a given radius */
double volumeFromRadius(double radius) {
    return (4.0/3.0) * PI * pow(radius,3.0f);
}

and I'm compiling with the command gcc -o sphere sphere.c

This compiles and runs fine in code::blocks on the Windows machines at uni, but on my Fedora 17 at home the command line compiler refuses to run. Any thoughts would be gratefully appreciated!

Blessings, Ian

Community
  • 1
  • 1
Ian Knight
  • 2,356
  • 2
  • 18
  • 22

1 Answers1

286

You need to link with the math library:

gcc -o sphere sphere.c -lm

The error you are seeing: error: ld returned 1 exit status is from the linker ld (part of gcc that combines the object files) because it is unable to find where the function pow is defined.

Including math.h brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a. You need to link your program with this library so that the calls to functions like pow() are resolved.

codaddict
  • 445,704
  • 82
  • 492
  • 529
  • 2
    This solved my issue. Nevertheless, I have 2 Ubuntu 20.04 boxes with Code::Blocks installed as IDE. One compiles the source code (including math functions) properly without `-lm`, and the other needs `-lm`. How can the second box compile without `-lm`? – geohei Sep 24 '20 at 07:17
  • 1
    @geohei, probably one window is compiling in release and the other in debug. What it seems is that compiling in release with codeblocks does not require `-lm`. – Alessandro Muntoni Nov 26 '20 at 16:11
  • Can you expand on what `-lm` does exactly? I've failed to find information about this flag in GCC online docs, and `man gcc`. – ichigolas Apr 07 '22 at 18:48
  • 4
    @ichigolas quite late for an answer, but for the record: `-l` means binary libraries to have in mind when linking. Whatever goes after `-l` is by default interpreted as part of a filename starting by `lib` and ending in `.a`. Hence `-lm` means link `libm.a` – Rafael Apr 27 '22 at 17:16
  • 1
    How silly that it's -lm instead of -lmath. – TyR Sep 17 '22 at 16:42