Home  >  Q&A  >  body text

为什么在linux下C语言中使用math.h中的公式编译时就要加参数-lm, windows中却不要?

我用的程序

#include<stdio.h>
#include<math.h>
#include<sys/time.h>
int main()
{
    struct timeval start,end;
    gettimeofday(&start,NULL);
    long long i;
    double temp;
    for(i=0;i<10000000;i++)
    {
        temp=sqrt(i);
    }
    gettimeofday(&end,NULL);
    long timeuse =1000000 * ( end.tv_sec - start.tv_sec )  \
    + end.tv_usec - start.tv_usec;
    printf("\ntime=%f\n",timeuse /1000000.0);
    return 0;
}
天蓬老师天蓬老师2742 days ago756

reply all(3)I'll reply

  • 怪我咯

    怪我咯2017-04-17 13:12:29

    gcc is a compiler. . It is at the same level as cl.exe.
    At most, your sqrt(4); can be directly optimized to the number 2,
    For example, in this case, you don’t need -lm

    C#include<stdio.h>
    int main(){
    printf("%d",(int)sqrt(4));
    }
    

    Cannot only deal with related link library issues,
    After all, no one knows whether the programmer will manually write a libm.so by himself.

    Every dynamic link library used must write the -l parameter yourself,
    For example, in this case, sqrt(4) will not be directly optimized into (double)2 by default:

    C#include<stdio.h>
    int main(){
    int i=4;
    printf("%d",(int)sqrt(i));
    }
    

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 13:12:29

    If this is the case, then it means that the windows compiler includes mathlib by default

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:12:29

    I don’t have the VC++ compiler at hand. It should have been merged into msvcrt. Like thread, you need -lpthread under Linux, but VC is not needed.
    http://blogs.msdn.com/b/vcblog/archive/2013/07/19/c99-library-support-in-visual-studio-2013.aspx

    reply
    0
  • Cancelreply