使用CMake静态链接到项目外的库

时间:2013-03-22 11:46:23

标签: c++ dependencies cmake

我想使用CMake将我的项目链接到我的共享库。该库只在少数项目之间共享,而且相当小,所以我真的想在链接之前构建它。每次构建它似乎比维护最新的预编译版本更好,因为我要与项目一起更改它。它是独立的,因为它包含我在下一个项目中几乎肯定需要的东西。

如何配置CMake来执行此操作?

相关项目的当前CMakeLists.txt如下所示:

find_package( Boost REQUIRED COMPONENTS unit_test_framework)

include_directories(${BaumWelch_SOURCE_DIR}/../../grzesLib/src
                    ${BaumWelch_SOURCE_DIR}/src 
                    ${Boost_INCLUDE_DIRS})

if(CMAKE_COMPILER_IS_GNUCXX)
    add_definitions(-g -std=c++11 -Wall -Werror -Wextra -pedantic -Wuninitialized)
endif()


# Create the unit tests executable
add_executable(
 baumwelchtests stateindextest.cpp baumiterationtest.cpp baumwelchtest.cpp sampleparameters.cpp sdetest.cpp
 # Key includes for setting up Boost.Test
 testrunner.cpp
 # Just for handy reference
 exampletests.cpp
)

# Link the libraries
target_link_libraries( baumwelchtests ${Boost_LIBRARIES} baumwelchlib grzeslib)

但显然编译失败了:

/usr/bin/ld: cannot find -lgrzeslib

1 个答案:

答案 0 :(得分:26)

您提到您想要构建库而不是使用预编译版本。如果库具有CMakeList,则应使用add_subdirectory(path/to/the/library/source/directory)添加它。然后它将成为您项目的子项目,您可以在CMakeList中使用其目标的名称。

请注意,虽然该命令名为add_ 子目录,但它可以是磁盘上的任意目录;它不必是主项目的源目录的子目录。如果它不是子目录,您还必须为它显式指定二进制目录。例如:

add_subdirectory(/path/to/the/library/source/directory subproject/grzeslib)

第二个参数,如果作为相对路径给出,则相对于CMAKE_CURRENT_BINARY_DIR进行解释。

相关问题