【问题标题】:Using CMake to statically link to a library outside of the project使用 CMake 静态链接到项目外部的库
【发布时间】:2013-03-12 06:18:23
【问题描述】:

我想使用 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

【问题讨论】:

  • 将.a添加到libname是否有效?
  • @drescherjm,这个库可能在那时甚至没有编译,而且我没有指定二进制文件的任何位置,所以我确信将 .a 添加到 libname 将无济于事。

标签: c++ dependencies cmake


【解决方案1】:

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

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

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

如果以相对路径的形式给出第二个参数,则解释为相对于CMAKE_CURRENT_BINARY_DIR

【讨论】:

  • 我试过了,但我收到以下错误:add_subdirectory not given a binary directory but the given source directory "/home/ga1009/PhD/cpp/grzesLib/src" is not a subdirectory of "/home/ga1009/PhD/cpp/pmi/cpp". When specifying an out-of-tree source a binary directory must be explicitly specified.。我该怎么办?
  • @Grzenio 我已将信息添加到答案中。
  • 我得到了与@Grzenio 相同的错误......它不允许我放置任何任意目录。
  • @WagnerPatriota 答案已经解决了这个问题:添加非子目录时还需要指定二进制目录。
  • @WagnerPatriota 根本不是这个意思。 CMAKE_CURRENT_BINARY_DIR 是一个只读变量(或者至少应该这样对待)。您需要将预期的二进制目录作为第二个参数传递给add_subdirectory如答案所示。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-17
相关资源
最近更新 更多