【问题标题】:How to make relative file path work in visual studio using cmake?如何使用 cmake 在 Visual Studio 中使相对文件路径工作?
【发布时间】:2017-11-10 23:02:04
【问题描述】:

我们正在使用 CMake 开发一个 c++ 项目。在项目中,我们使用std::ifstream 类引用一些资源文件,例如resources/file.txt(直接位于项目文件夹内)。现在的问题是,虽然我们的其他团队成员在使用 Linux 时可以引用这些文件,但我不能(我使用的是 Visual Studio 2017)。

如何设置 CMake 或 Visual Studio,以便在不更改路径的情况下引用这些文件?我仍然是使用 CMake 的一个相当大的新手,但我没有找到任何有效的方法。

编辑:
显示问题的最少代码:

#include <iostream>
#include <fstream>
#include <string>

std::string read_file(std::string filename)
{
    std::string result = "";

    std::ifstream file(filename);
    if (!file.is_open())
    {
        std::cout << "Could not open file " << filename.c_str() << "." << std::endl;
        return result;
    }

    std::string line;
    while (getline(file, line))
        result += line + '\n';
    return result;
}

int main(int argc, char *argv[])
{
    std::string fileContent = read_file("src/Test_File.txt");

    if (fileContent.compare(""))
    {
        std::cout << fileContent.c_str() << std::endl;
    }

    return 0;
}

此程序应加载位于 src 文件夹内的“Test_File.txt”,文件夹结构为:

    • main.cpp
    • CMakeList.txt
    • Test_File.txt
  • CMakeList.txt

这里的问题是程序找不到 Text_File.txt 而其他团队成员没有这样的问题。绝对路径当然有效,但它们显然不是要走的路。

我已经尝试使用 VS_DEBUGGER_WORKING_DIRECTORY 参数和 set_target_properties(${PROJECT_NAME} PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")add_executable(${PROJECT_NAME} "${CMAKE_CURRENT_SOURCE_DIR}/main.cpp") 之后,但这似乎也不起作用。

【问题讨论】:

  • The problem now is that, while our other team members can reference these files as they use Linux, I cannot (I am using Visual Studio 2017). - 为什么您无法访问这些文件?最有可能的原因是可执行文件的不同位置,或不同的工作目录(运行可执行文件的目录)。这取决于您的可执行文件的代码,但您不显示它。
  • 我已经尝试过设置不同的工作目录,尽管我可能做错了。你到底需要什么代码?谢谢。
  • What code do you need exactly? - 可执行文件(C++ 文件)的代码,格式为minimal reproducible exampleI already tried set a different working directory although I may have done it incorrectly. - 究竟如何您尝试设置它?您希望我们(Stack Overflow 社区)为您提供帮助,但提供的信息太少,所以连问题都不清楚。
  • 我现在更新了这个问题。谢谢。
  • 好吧,问题变得更清楚了。因此,您想在 Visual Studio 2017 中运行可执行文件时为其设置工作目录。您是否见过 that question,关于非常相似的事情?您使用哪个 CMake 版本?您在CMakeLists.txt 开头将哪个版本传递给cmake_minimum_required 命令?

标签: c++ visual-studio cmake


【解决方案1】:

多亏了@Tsyvarev,经过多次尝试,我终于可以正常工作了。正如in this question they brought up 所述,设置“currentDir”有效。对我来说,它以前不起作用,因为 "name""projectTarget" 设置不正确。

我现在在修复"name""projectTarget" 值后添加了"currentDir": "${workspaceRoot}",它起作用了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    相关资源
    最近更新 更多