cmathflow-control

In the C program why am I getting an error of sample.c:(.text+0xb4): undefined reference to `pow


I am making a program C program that finds out whether a number is an Armstrong number or not. Here's the code:

#include <stdio.h>
#include <math.h>
int main(){
    int inp,count,d1,d2,rem;
    float arm;
    printf("the number: ");
    scanf("%d",&inp);

    d1 = inp;
    d2 = inp;
    // for counting the number of digits
    while(d1 != 0){
        d1 /= 10; 
        ++count;
    }
    //for checking whether the number is anarmstrong number or not
    while(d2 != 0){
        rem = (d2 % 10);
        arm += pow(rem,count);
        d2 /= 10;
    }
    printf("%f",arm);
    return 0;

}

(file name: sample.c)

I expect the program to show the output as:

the number: 

but it shows the following error:

usr/bin/ld: /tmp/ccleyeW0.o: in function `main':
sample.c:(.text+0xb4): undefined reference to `pow'
collect2: error: ld returned 1 exit status

I have even used the command GCC -o sample sample.c -lm but still getting an error. So I would like to know what is causing this error and how can I resolve the issue.


Solution

  • As indicated in the comments above, you should compile your program using gcc -o sample sample.c -lm. The -lm argument ensures that your program is linked against the math library.

    Besides that, it is not only good style, but necessary to initialise variables in C before you use them. In this case, the variables arm and count are not initialised. Especially the value of arm will certainly cause trouble, because it will have the value of whatever is at its assigned memory location (garbage value), when you run your program, which leads to non-deterministic behaviour. Initialising both variables to 0 should fix your code.