使用CMake静态链接到项目外部的库 [英] Using CMake to statically link to a library outside of the project

查看:546
本文介绍了使用CMake静态链接到项目外部的库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to use CMake to link my project to my shared library. The library is only shared between a handful of projects and is rather small, so I would really like to build it before it is linked. Building it every time seems a better idea than having to maintain an up-to-date precompiled version, because I ten to change it together with the project. It is separate, because it contains stuff I will almost certainly need in the next project.

我如何配置CMake来做呢?

How can I configure CMake to do it?

我的当前CMakeLists.txt为相关项目看起来像这样:

My current CMakeLists.txt for the relevant project looks like this:

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


推荐答案

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

You mentioned you'd like to build the library rather than use a precompiled version. If the library has a CMakeList, you should add it using add_subdirectory(path/to/the/library/source/directory). It will then become a subproject of your project and you can use names of its targets normally in your CMakeList.

请注意,虽然命令被称为add_ ,它可以是磁盘上的任意目录;它不必是主项目的源目录的子目录。如果它不是一个子目录,你必须显式地为它指定一个二进制目录。示例:

Note that while the command is called add_subdirectory, it can be an arbitrary directory on disk; it doesn't have to be a subdirectory of the master project's source dir. In case it's not a subdirectory, you have to explicitly specify a binary directory for it as well. Example:

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

第二个参数,如果作为相对路径给出,则相对于 CMAKE_CURRENT_BINARY_DIR

The second argument, if given as a relative path, is interpreted relative to CMAKE_CURRENT_BINARY_DIR.

这篇关于使用CMake静态链接到项目外部的库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆