Thread: error when using math.h

  1. #1
    Registered User
    Join Date
    Apr 2005
    Posts
    5

    error when using math.h

    Hi all,

    I have the following code:

    Code:
    #include <math.h>
    ...
    ...
    double x;
    int y, i;
    x = floor( (double)y/4 );
    i = (int)fmod(x, 2);
    and i always got the following errors:
    undefined reference to 'floor'
    undefined reference to 'fmod'

    What s wrong with the code? I already include math.h...

    Thank you!

  2. #2
    Registered User Micko's Avatar
    Join Date
    Nov 2003
    Posts
    715
    With that code I see problem you dind't initialize y. Aside that I see no other problems. Which compiler are you using?
    Gotta love the "please fix this for me, but I'm not going to tell you which functions we're allowed to use" posts.
    It's like teaching people to walk by first breaking their legs - muppet teachers! - Salem

  3. #3
    Registered User
    Join Date
    Apr 2005
    Posts
    5
    I know already...

    I need to add -lm into the command gcc

  4. #4
    Registered User
    Join Date
    Apr 2005
    Posts
    5
    But still don't know what is the reason of adding -lm...

  5. #5
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    The math library is where your math functions are defined. The header just tells the compiler that some functions exist and how they are to be used. The linker needs to know where these functions are.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  6. #6
    Registered User
    Join Date
    Mar 2005
    Posts
    38
    The linker must know which libraries to link to. With -lm, you link to functions from math.h.

  7. #7
    Obsessed with C chrismiceli's Avatar
    Join Date
    Jan 2003
    Posts
    501
    The reason people forget to add the -lm when using the math library is because they think it is part of the standard. Well it is, but they decided to link the c library automatically to all programs, just not the math library.
    Help populate a c/c++ help irc channel
    server: irc://irc.efnet.net
    channel: #c

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. math.h
    By tsutharssan in forum C Programming
    Replies: 3
    Last Post: 07-03-2009, 02:24 PM
  2. Trig Functions without math.h
    By daltore in forum C Programming
    Replies: 13
    Last Post: 12-29-2008, 04:47 PM
  3. cosine series with out using math.h
    By indrajit_muk in forum C Programming
    Replies: 5
    Last Post: 12-16-2008, 08:17 PM
  4. undefined reference to `sqrt' when using math.h
    By Milhas in forum C Programming
    Replies: 4
    Last Post: 03-31-2008, 06:11 PM
  5. using round from math.h
    By axr0284 in forum C Programming
    Replies: 5
    Last Post: 05-02-2006, 11:23 AM