简体   繁体   English

如何获得 CMake 单元测试的相对路径?

[英]How to get a relative path for CMake unit tests?

I have a project built with CMake that uses Catch2 for unit tests.我有一个用 CMake 构建的项目,它使用 Catch2 进行单元测试。 Some of the unit tests exercise code that loads data from a file like this:一些单元测试会执行从文件加载数据的代码,如下所示:

std::string resource_dir = "TEST_CWD/resources/";
std::ifstream infile{resource_dir + "datafile.txt"}

The question is how to properly get the value of TEST_CWD .问题是如何正确获取TEST_CWD的值。

The directory structure is simple (and not set in stone):目录结构很简单(不是一成不变的):

my_project/
    test/
        resources/datafile.txt
        loader_test.cpp

Leaving TEST_CWD blank sometimes works, but breaks when running tests through an IDE.TEST_CWD留空有时有效,但在通过 IDE 运行测试时会中断。 Setting an environment variable with the absolute path also works, but will break on others' machines.使用绝对路径设置环境变量也有效,但会在其他机器上中断。 Similarly forcing all users to manually set environment variables is user unfriendly.同样,强制所有用户手动设置环境变量对用户不友好。

What is a good way to specify relative file paths in CMake projects?在 CMake 项目中指定相对文件路径的好方法是什么?

I don't know about relative paths, but you can use ${CMAKE_SOURCE_DIR} to get the path to the top-level directory of your project-- where the main CMakeLists.txt file is.我不知道相对路径,但您可以使用${CMAKE_SOURCE_DIR}来获取项目顶级目录的路径 - 主 CMakeLists.txt 文件所在的位置。

From the CMake docs for CMAKE_SOURCE_DIR :来自CMAKE_SOURCE_DIRCMake 文档

The path to the top level of the source tree.源树顶层的路径。

This is the full path to the top level of the current CMake source tree.这是当前 CMake 源代码树顶层的完整路径。 For an in-source build, this would be the same as CMAKE_BINARY_DIR.对于源内构建,这与 CMAKE_BINARY_DIR 相同。

Then you can just base all your paths off of this.然后,您可以将所有路径都以此为基础。 For example, in a CMake script, you could write ${CMAKE_SOURCE_DIR}/resources/datafile.txt .例如,在 CMake 脚本中,您可以编写${CMAKE_SOURCE_DIR}/resources/datafile.txt

Edit:编辑:

If you need access to this value in your C++ code itself, you could use the configure_file command.如果您需要在 C++ 代码本身中访问此值,则可以使用configure_file命令。 For example you could create a file called something like Config.h.in ...例如,您可以创建一个名为Config.h.in类的文件...

// Config.h.in

#ifndef CONFIG_H
#define CONFIG_H

#define SOURCE_DIR "${CMAKE_SOURCE_DIR}"

#endif

... and then in your CMakeLists.txt file, ...然后在你的 CMakeLists.txt 文件中,

configure_file(Config.h.in ${CMAKE_BINARY_DIR}/Config.h)

include_directories(${CMAKE_BINARY_DIR})

Then you could include Config.h like a normal header, and be on your way!然后你可以像普通的头文件一样包含Config.h ,然后就可以了!

Single variable shortcut单变量快捷方式

Just use a preprocessor macro.只需使用预处理器宏。 In the CMakeLists.txt in test/ :test/CMakeLists.txt中:

target_compile_definitions(target_name PUBLIC TEST_RESOURCE_DIR="${CMAKE_CURRENT_SOURCE_DIR}/resources/")

in C++:在 C++ 中:

std::string resource_dir = TEST_RESOURCE_DIR;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM