C programming using linux terminal

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sudeep93
    New Member
    • Feb 2013
    • 1

    C programming using linux terminal

    Whenever i run this code(on linux terminal):

    Code:
    #include <stdio.h>
    #include <math.h>
    int main()
    {
    double x,y;
    printf ("enter the angle between the two sides(in radians): \n");
    scanf ("%lf",&x);
    y= cos(x);
    printf ("the cosine of the angle is: %lf\n",y);
    return 0;
    }
    I always get this error:

    Code:
    /tmp/cckIyjg6.o: In function `main':
    CosineRule.c:(.text+0x33): undefined reference to `cos'
    collect2: ld returned 1 exit status
    whats the problem with my code? please help..
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    There are no errors in the code you posted.

    The error is in CosineRule.c. Did you include <math.h> in that file?

    Comment

    • Luuk
      Recognized Expert Top Contributor
      • Mar 2012
      • 1043

      #3
      @weaknessforcat s: it is there at line 2 ...

      i googled and found this:
      use: cc CosineRule.c -o CosineRule -lm
      (http://www.cs.cf.ac.uk/Dave/C/node17.html)

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        When you include <math.h> it is a little bit like telling the compiler: "Yes, I know these functions (such as cos) are not in my source file; but trust me, you'll have them when you need them."
        That error message is the compiler's way of saying: "You let me down -- I didn't have this function when I needed it."
        The -lm command line argument to the compiler directs it to look in library m (file libm.a) for anything that it still needs. As it happens, libm is where the <math.h> functions are kept (m is for math) so now the compiler is happy because it has everything it needs.

        You might ask: "Why isn't libm automatically included?" The simple answer is that the C Standard does not require that behavior. The real answer is that C allows you the leeway to write your own cos function -- and you can even go so far as to write a cos function that has nothing to do cosines. I'm not suggesting it would be wise to do this, but it is allowed.

        Comment

        Working...