tags:

views:

911

answers:

3
+1  Q: 

erf(x) and math.h

According to this site the error function erf(x) comes from math.h. But actually looking in math.h, it isn't there, and gcc cannot compile the following test program while g++ can:

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

int main(int argc, char* argv[]) {
  double x;
  double erfX;
  x = 1.0;
  erfX = erf(x);

  printf("erf(%f) = %f", x, erfX);
}

$ gcc mathHTest.c
/tmp/ccWfNox5.o: In function `main':
mathHTest.c:(.text+0x28): undefined reference to `erf'
collect2: ld returned 1 exit status
$ g++ mathHTest.c

What does g++ pull in that gcc doesn't? Looking in /usr/include, the only place I could find erf(x) was in tgmath.h, which I don't include. So g++ must be grabbing different headers than gcc, but which ones?

EDIT: I wasn't linking in libm with gcc, hence the link error. However, I still don't understand why erf() is not in math.h. Where is it coming from?

+2  A: 

You need to link the math library (libm) too:

$ gcc mathHTest.c -lm

All of the normal math library functions are actually there, and not in the standard C library (libc).

According to my tests, g++ does include libm automatically, but gcc doesn't.

Alnitak
+2  A: 

'erf' is actually declared in bits/mathcalls.h, which is #included by math.h. The actual declaration is heavily obscured by macro magic to make it do the right thing for both C and C++

Chris Dodd
A: 

I had the same problem using gcc from cygwin on a x86 processor. The "-lm" library include parameter (after the file list!) worked perfectly.