如何获得CMake单元测试的相对路径? [英] How to get a relative path for CMake unit tests?

查看:85
本文介绍了如何获得CMake单元测试的相对路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用CMake构建的项目,该项目使用Catch2进行单元测试。一些单元测试练习代码从这样的文件中加载数据:

I have a project built with CMake that uses Catch2 for unit tests. 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"}

问题是如何正确获取 TEST_CWD 的值。

The question is how to properly get the value of TEST_CWD.

目录结构很简单(并且不是一成不变的):

The directory structure is simple (and not set in stone):

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

TEST_CWD 留空有时会起作用,但在运行时会中断通过IDE进行测试。使用绝对路径设置环境变量也可以,但是会在其他计算机上中断。同样,强制所有用户手动设置环境变量对用户也不友好。

Leaving TEST_CWD blank sometimes works, but breaks when running tests through an 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.

在CMake项目中指定相对文件路径的好方法是什么?

What is a good way to specify relative file paths in CMake projects?

推荐答案

我不知道相对路径,但是您可以使用 $ {CMAKE_SOURCE_DIR} 获取项目的顶级目录的路径-主CMakeLists.txt文件所在的位置。

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 的CMake文档

From the CMake docs for CMAKE_SOURCE_DIR:


到源树顶层的路径。

The path to the top level of the source tree.

这是到当前CMake源树顶层的完整路径。对于源内构建,这将与CMAKE_BINARY_DIR相同。

This is the full path to the top level of the current CMake source tree. For an in-source build, this would be the same as CMAKE_BINARY_DIR.

然后,您可以基于此创建所有路径。例如,在CMake脚本中,您可以编写 $ {CMAKE_SOURCE_DIR} /resources/datafile.txt

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.

编辑:

如果您需要在C ++代码本身中访问此值,则可以使用 configure_file 命令。例如,您可以创建名为 Config.h.in ...

If you need access to this value in your C++ code itself, you could use the configure_file command. For example you could create a file called something like Config.h.in...

// Config.h.in

#ifndef CONFIG_H
#define CONFIG_H

#define SOURCE_DIR "${CMAKE_SOURCE_DIR}"

#endif

...,然后在您的CMakeLists.txt文件中,

... and then in your CMakeLists.txt file,

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

include_directories(${CMAKE_BINARY_DIR})

然后,您可以像普通标头一样包含 Config.h 并成为

Then you could include Config.h like a normal header, and be on your way!

单变量快捷方式

只需使用预处理程序宏即可。在 test / CMakeLists.txt 中:

Just use a preprocessor macro. In the CMakeLists.txt in test/:

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

在C ++中:

std::string resource_dir = TEST_RESOURCE_DIR;

这篇关于如何获得CMake单元测试的相对路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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