C++ error: undefined reference to 'clock_gettime' and 'clock_settime'

后端 未结 4 408
予麋鹿
予麋鹿 2020-12-02 07:10

I am pretty new to Ubuntu, but I can\'t seem to get this to work. It works fine on my school computers and I don\'t know what I am not doing. I have checked usr/in

相关标签:
4条回答
  • 2020-12-02 07:45

    Since glibc version 2.17, the library linking -lrt is no longer required.

    The clock_* are now part of the main C library. You can see the change history of glibc 2.17 where this change was done explains the reason for this change:

    +* The `clock_*' suite of functions (declared in <time.h>) is now available
    +  directly in the main C library.  Previously it was necessary to link with
    +  -lrt to use these functions.  This change has the effect that a
    +  single-threaded program that uses a function such as `clock_gettime' (and
    +  is not linked with -lrt) will no longer implicitly load the pthreads
    +  library at runtime and so will not suffer the overheads associated with
    +  multi-thread support in other code such as the C++ runtime library.
    

    If you decide to upgrade glibc, then you can check the compatibility tracker of glibc if you are concerned whether there would be any issues using the newer glibc.

    To check the glibc version installed on the system, run the command:

    ldd --version
    

    (Of course, if you are using old glibc (<2.17) then you will still need -lrt.)

    0 讨论(0)
  • 2020-12-02 07:50

    example:

    c++ -Wall filefork.cpp -lrt -O2
    

    For gcc version 4.6.1, -lrt must be after filefork.cpp otherwise you get a link error.

    Some older gcc version doesn't care about the position.

    0 讨论(0)
  • 2020-12-02 07:59

    I encountered the same error. My linker command did have the rt library included -lrt which is correct and it was working for a while. After re-installing Kubuntu it stopped working.

    A separate forum thread suggested the -lrt needed to come after the project object files. Moving the -lrt to the end of the command fixed this problem for me although I don't know the details of why.

    0 讨论(0)
  • 2020-12-02 08:05

    Add -lrt to the end of g++ command line. This links in the librt.so "Real Time" shared library.

    0 讨论(0)
提交回复
热议问题