user1696230
user1696230

Reputation:

C programming - "Undefined symbol referenced in file"

I am trying to write a program to approximate pi. It basically takes random points between 0.00 and 1.00 and compares them to the bound of a circle, and the ratio of points inside the circle to total points should approach pi (A very quick explanation, the specification goes in depth much more).

However, I am getting the following error when compiling with gcc:

Undefined                       first referenced
symbol                          in file
pow                             /var/tmp//cc6gSbfE.o
ld: fatal: symbol referencing errors. No output written to a.out
collect2: ld returned 1 exit status

What is happening with this? I've never seen this error before, and I don't know why it's coming up. Here is my code (though I haven't fully tested it since I can't get past the error):

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

int main(void) {
    float x, y;
    float coordSquared;
    float coordRoot;
    float ratio;
    int n;
    int count;
    int i;

    printf("Enter number of points: ");
    scanf("%d", &n);

    srand(time(0));

    for (i = 0; i < n; i++) {
        x = rand();
        y = rand();

        coordSquared = pow(x, 2) + pow(y, 2);
        coordRoot = pow(coordSquared, 0.5);

        if ((x < coordRoot) && (y < coordRoot)) {
            count++;
        }
    }

    ratio = count / n;
    ratio = ratio * 4;

    printf("Pi is approximately %f", ratio);

    return 0;
}

Upvotes: 1

Views: 32941

Answers (3)

justinyu
justinyu

Reputation: 31

need to Link with -lm. gcc test.c -o test -lm

Upvotes: 3

Michael F
Michael F

Reputation: 40830

The error is produced by the linker, ld. It is telling you that the symbol pow cannot be found (is undefined in all the object files handled by the linker). The solution is to include the library which includes the implementation of the pow() function, libm (m for math). [1] Add the -lm switch to your compiler command line invocation (after all the source file specifications) to do so, e.g.

gcc -o a.out source.c -lm

[1] Alternatively, you could have your own implementation of pow() in a separate translation unit or a library, but you would still have to tell the compiler/linker where to find it.

Upvotes: 2

Aniket Inge
Aniket Inge

Reputation: 25705

use -lm during compilation(or linking) to include math library.

Like this: gcc yourFile.c -o yourfile -lm

Upvotes: 6

Related Questions