我最近正在使用yaml-cpp库。我按照“ yaml-cpp-config.cmake.in”中的配置文件进行操作,
# - Config file for the yaml-cpp package
# It defines the following variables
# YAML_CPP_INCLUDE_DIR - include directory
# YAML_CPP_LIBRARIES - libraries to link against
# Compute paths
get_filename_component(YAML_CPP_CMAKE_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH)
set(YAML_CPP_INCLUDE_DIR "@CONFIG_INCLUDE_DIRS@")
# Our library dependencies (contains definitions for IMPORTED targets)
include("${YAML_CPP_CMAKE_DIR}/yaml-cpp-targets.cmake")
# These are IMPORTED targets created by yaml-cpp-targets.cmake
set(YAML_CPP_LIBRARIES "@EXPORT_TARGETS@")
根据第8行和第14行(或注释部分),我编辑了CMakeLists.txt和test.cpp,就像
cmake_minimum_required(VERSION 3.5)
project(yaml_test)
find_package(yaml-cpp)
include_directories(${YAML_CPP_INCLUDE_DIRS})
add_executable(yaml_test src/test.cpp)
target_link_libraries(yaml_test ${YAML_CPP_LIBRARIES})
#include <yaml-cpp/yaml.h>
int main()
{
YAML::Node node = YAML::LoadFile("test.yaml");
return 0;
}
我知道了
CMakeFiles/yaml_test.dir/src/test.cpp.o: In function `main':
test.cpp:(.text+0xf9): undefined reference to `YAML::LoadFile(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
collect2: error: ld returned 1 exit status
CMakeFiles/yaml_test.dir/build.make:94: recipe for target 'yaml_test' failed
make[2]: *** [yaml_test] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/yaml_test.dir/all' failed
make[1]: *** [CMakeFiles/yaml_test.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2
我从undefined reference to YAML::LoadFile找到了解决方案
将我的CMakeLists.txt更改为
cmake_minimum_required(VERSION 3.5)
project(yaml_test)
find_package(yaml-cpp)
include_directories(${YAMLCPP_INCLUDE_DIRS})
add_executable(yaml_test src/test.cpp)
target_link_libraries(yaml_test ${YAMLCPP_LIBRARIES})
我可以成功构建代码。
我的问题是如何直接从yaml-cpp包的CMakeLists.txt或配置文件中分辨出正确的“ include_directories”和“ target_link_libraries”?
有人可以帮助我吗?谢谢!
答案 0 :(得分:1)
我的问题是如何直接从yaml-cpp包的CMakeLists.txt或配置文件中分辨出正确的“ include_directories”和“ target_link_libraries”?
只需确保您查看CMake 实际使用的配置文件。
例如。 yaml-cpp-config.cmake.in
只是将来yaml-cpp-config.cmake
的模板,但是您的系统可能针对同一软件包具有其他配置文件。
CMake将配置文件的确切路径存储在<PackageName>_CONFIG
变量中,因此如果不确定,可以打印此变量的值:
...
find_package(yaml-cpp)
message(STATUS "Used config file: ${yaml-cpp_CONFIG}")
当读取配置文件时,除了顶部的文档外,它对于检查set
行很有用,该行为文档变量*_LIBRARY
或*_LIBRARIES
分配了一个值。如果该值为空,则“ config”文件可能损坏,并且很有可能无法使用已记录的变量。但是您可以使用导入的目标,请参见下文。
请注意,大多数“配置”文件都提供了导入的目标,供其他代码使用。
此机制优于使用变量*_INCLUDE_DIR
和*_LIBRARIES
。如果找不到有关要使用的确切导入目标的文档,请查看配置文件中*_LIBRARIES
变量的值:该变量可能包含导入目标的列表,您可以尝试通过以下方式在代码中使用target_link_libraries
。
有关更多详细信息,请查看find_package
documentation。