How to link to the C math library with CMake?

前端 未结 2 1702
名媛妹妹
名媛妹妹 2020-11-29 09:10

How do I add the math library to my CMake file? This post references adding a target link library, yet I am not too familiar with C. An Additional post - Could

2条回答
  •  不知归路
    2020-11-29 09:48

    For various targets it's a good idea to test if adding a library is needed or not and if so where it's located of how it's named. Here's one way to do it:

    :
    include(CheckLibraryExists)
    
    CHECK_LIBRARY_EXISTS(m sin "" HAVE_LIB_M)                                                                                                
                                                                                                                                             
    if (HAVE_LIB_M)                                                                                                                          
        set(EXTRA_LIBS ${EXTRA_LIBS} m)                                                                                                      
    endif (HAVE_LIB_M)
    
    :
    //More tests & build-up of ${EXTRA_LIBS}
    :
    
    add_executable(ch4 ch4.c)
    target_link_libraries(ch4 PUBLIC ${EXTRA_LIBS})
    

    For targets where libm is part of libc, the above test should fail, i.e. ${EXTRA_LIBS} will miss it and target_link will not try to add.

提交回复
热议问题