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

Grz*_*nio 16 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)
Run Code Online (Sandbox Code Playgroud)

但显然编译失败了:

/usr/bin/ld: cannot find -lgrzeslib
Run Code Online (Sandbox Code Playgroud)

Rei*_*ica 26

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

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

add_subdirectory(/path/to/the/library/source/directory subproject/grzeslib)
Run Code Online (Sandbox Code Playgroud)

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

  • 我试过了,但是我收到以下错误:`add_subdirectory没有给出二进制目录,但给定的源目录"/ home/ga1009/PhD/cpp/grzesLib/src"不是"/ home/ga1009/PhD /"的子目录CPP/PMI/CPP".指定树外源时,必须明确指定二进制目录.我该怎么办? (2认同)
  • @WagnerPatriota 这根本不是我的意思。* `CMAKE_CURRENT_BINARY_DIR` 是一个只读变量(或者至少应该这样对待)。您需要将预期的二进制目录作为第二个参数传递给“add_subdirectory”,*如答案所示。* (2认同)