CMake: Link a library to library

后端 未结 2 1197
無奈伤痛
無奈伤痛 2021-02-04 00:34

I have a problem with cmake. I have, lets say, CMakeLists1 which has a subdirectory where CMakeLists2 is.

In CMakeLists2 my target is a static library. And I want to lin

2条回答
  •  日久生厌
    2021-02-04 01:15

    I think it's CMake's default behavior to not link project2 to the external library, but to link both libraries to the executable. From the book "Mastering CMake".

    Since static libraries do not link to the libraries on which they depend, it is important for CMake to keep track of the libraries so they can be specified on the link line of the executable being created.

    You could try to use an absolute path in your CMakeLists2:

    add_library (project2 ${sources})
    target_link_libraries (project2 "path to ext lib"/"name of ext lib")
    

    or you could add

    link_directories ("path_to_library")
    

    to the CMakeLists file of project1.

    If you really want to do something like in Visual Studio, you could probably use the command given in this answer to build a custom_command in CMake. It probably would look something like this (I didn't test it).

    set(EXT_LIB "path_to_library/name_of_external_lib") 
    set(BIG_LIB "path_to_big_lib/name_of_big_lib")
    add_library (project2 ${sources})
    get_property(PROJ2_LOC TARGET project2 PROPERTY LOCATION)
    
    add_custom_command(OUTPUT ${BIG_LIB} 
                       DEPENDS ${EXT_LIB} project2
                       COMMAND "lib.exe /OUT:${BIG_LIB} ${EXT_LIB} ${PROJ2_LOC} )
    

    Then you could link your executable with ${BIG_LIB}.

    Some things you have to consider:

    • Maybe you have to use LOCATION_CONFIG (CMake docs, I found the get_property command in this answer )
    • link.exe has to be in your path
    • watch the scope of the BIG_LIB variable if you want to use it in an other CMakeLists.txt

提交回复
热议问题