LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Problem with math.h (https://www.linuxquestions.org/questions/programming-9/problem-with-math-h-145176/)

loke137 02-12-2004 05:54 AM

Problem with math.h
 
I should be bashed to death for not being able to do this :) ...I just started learning C, I am using gcc 3.2.3 on a linux box. This is the code I wrote, which finds prime numbers below 100:
Code:

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


main ()
{
int i, j;
printf ("%d\n", 2);

for (i=3; i<100; i=i+1)
        {
        for (j=2; j<i;j=j+1)
                {
                if (i%j ==0)
                        break;
                if (j > sqrt(i))
                        {
                        printf ("%d\n");
                        break;
                        }
                }
        }
return 0;
}

And this is the error msg I get after attempting to compile:
Code:

bash-2.05b$ gcc primo.c -o primo
/tmp/ccZdYpje.o(.text+0x65): In function `main':
: undefined reference to `sqrt'
collect2: ld returned 1 exit status
bash-2.05b$

Isn`t sqrt defined in math.h??

Thanks

jim mcnamara 02-12-2004 06:13 AM

Use gcc -lm -o myprog myprog.c

The "-lm" invokes linking of the math library.

Hko 02-12-2004 06:22 AM

Re: Problem with math.h
 
Quote:

Originally posted by loke137
Isn`t sqrt defined in math.h??
Well, yes, it is. But in case of the math library, you also need to link with the math library. It's very understandable that you, as a beginner, didn't know this as for most standard things you #include there's no need for linking with seperate libraries.

Assuming you c-file is called "prime.c", and you want the executable be called "prime", compile with this command line
Code:

gcc -lm -o prime prime.c
"-lm" makes sure the math library is linked.

You'll also see another error, because you forgot to pass the variable i to the printf statement. Change the line to:
Code:

    printf ("%d\n", i);
Also, it's better to declare main() as "int main()". If you don't specify "int" as the return type of main(), you'll get a warning. Not a big deal though, it's only warning, not an error.

Compile with this to make the compiler report all possible warnings:
Code:

gcc -Wall -pedantic -lm -o prime prime.c

loke137 02-12-2004 06:38 AM

Thank you...so it was a problem about compiler knowledge :)

Hko 02-12-2004 07:12 AM

To be pedantically precise: it was a problem about linking knowledge :-)


All times are GMT -5. The time now is 07:42 AM.