本文介绍了如何设置cmake,以便将txt文件作为资源添加到工作目录中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CMakeLists.txt

CMakeLists.txt

cmake_minimum_required(VERSION 3.8)
project(untitled)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)
add_executable(untitled ${SOURCE_FILES})

main.cpp

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
    string line;
    ifstream myfile ("test.txt");
    if (myfile.is_open())
    {
        while ( getline (myfile,line) )
        {
            cout << line << '\n';
        }
        myfile.close();
    }

    else cout << "Unable to open file";

    return 0;
}

我得到此输出无法打开文件。
文件 test.txt CMakeLists.txt main.cpp 在同一目录中。 IDE是CLion。

I got this output "Unable to open file".The files test.txt, CMakeLists.txt and main.cpp are in the same directory. IDE is CLion.

如何设置 CMakeLists.txt ,以便添加 test.txt 文件作为资源进入工作目录?

How to set the CMakeLists.txt, in order to add the test.txt file into the working directory as resource?

推荐答案

您可以使用 file(COPY 惯用法:

file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/test.txt
     DESTINATION ${CMAKE_CURRENT_BINARY_DIR})

但我也可以建议和 COPYONLY 选项,这样,当修改 test.txt 时,CMake将重新配置并重新生成内部版本。 ,只需使用 file(COPY

But may I also suggest configure_file with the COPYONLY option. In this way, when test.txt is modified, CMake will reconfigure and regenerate the build. If you don't need that, just use file(COPY

configure_file(${CMAKE_CURRENT_SOURCE_DIR}/test.txt
    ${CMAKE_CURRENT_BINARY_DIR} COPYONLY)

您还将看到很多使用 add_custom_command 复制文件,但是在必须在构建步骤之间复制文件时,at会更有用:

You will also see many people using add_custom_command to copy files, but that is more useful when you must copy a file in between build steps:

add_custom_command(
    TARGET untitled POST_BUILD
    COMMAND ${CMAKE_COMMAND} -E copy
            ${CMAKE_SOURCE_DIR}/test.txt
            ${CMAKE_CURRENT_BINARY_DIR}/test.txt)

在您的情况下,我认为第一个示例最合适,但是现在您的工具箱中有适用于所有情况的工具。

I think in your case, the first example is most appropriate, but now you have tools in your toolbox for all scenarios.

这篇关于如何设置cmake,以便将txt文件作为资源添加到工作目录中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 00:09