Strange Issue with GCC

I'm currently trying to learn C/C++ on my own in a Linux environment, but I've came up against an issue whilst using GCC that just doesn't make any sense to me.

You see, I'm trying to compile an example program I found in an online tutorial, as shown below:

1
2
3
4
5
6
7
8
9
#include <math.h>

main()
{
  int i;
  printf("\t Number \t\t Square of Number\n\n");
  for(i = 0; i <= 360; ++i)
    printf("\t %d \t\t\t %d \n", i, sqrt((double) i));
}


But GCC gives me the following output when I try to compile:

jwesleycooper@linux-twom:~/C> gcc Exercise12172.c
Exercise12172.c: In function ‘main’:
Exercise12172.c:6:3: warning: incompatible implicit declaration of built-in function ‘printf’
/tmp/ccy7FQEn.o: In function `main':
Exercise12172.c:(.text+0x3f): undefined reference to `sqrt'
collect2: ld returned 1 exit status


Can anyone explain to me why this is happening, and how I might correct it?

Thanks!

EDIT: The tutorial on this site appears to be geared solely at Windows users (I've yet to find an iostream header for Linux), so is there anywhere I might find a proper *Linux* C/C++ tutorial?
Last edited on
You need to #include <stdio.h> and link to the math library

(I've yet to find an iostream header for Linux)
What?
That's because you're mixing up C and C++.
They're two different languages and there is no iostream header in C.
There certainly is no such language as "C/C++".
You need to #include <stdio.h> and link to the math library

Ok, but how do I link to the math library?

That's because you're mixing up C and C++.
They're two different languages and there is no iostream header in C.
There certainly is no such language as "C/C++".

I'm trying to learn both of them, sorry that I got mixed up. So I just need to make sure that the file extension is .cpp if I want to use C++ then?
Last edited on
Ok, but how do I link to the math library?
-lm
-lm

Could you please be just a *little* less cryptic Bazzy? I am quite new at this, you know.
Last edited on
pass it as argument to gcc
Ok, that worked now... so what exactly do the 'l' and 'm' flags do? The command gcc -v --help says it's this this:

-l LIBNAME, --library LIBNAME
                              Search for library LIBNAME

and this:

-m EMULATION                Set emulation

But that doesn't really help me understand what it's actually doing...
Last edited on
-lm links the math library, libm.a. It is one command-line option, not two.
the easy way, with simple standalone files
is to use 'make' and implicit rules...

(note: remove extension on using make)

1
2
3
$ export LDLIBS=-lm
$ make Exercise12172
   cc     Exercise12172.c  -lm -o Exercise12172


much less typing, the programmer's skill of laziness
Last edited on
Thanks for your explanations and advice everyone, you've all been very helpful! :-)
Last edited on
Topic archived. No new replies allowed.