C programming - "Undefined symbol referenced in file"

25,849

Solution 1

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

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

Solution 2

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

Solution 3

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.

Share:
25,849
alk
Author by

alk

Be thoughtful and attentive ... - but just do it! #SOreadytohelp

Updated on May 14, 2020

Comments

  • alk
    alk almost 4 years

    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;
    }
    
    • Daniel Fischer
      Daniel Fischer over 11 years
      Just a note, don't use pow(x,2), use x*x. Simpler and faster.