How to set cmake, in order to add txt files into w

2019-07-16 12:21发布

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;
}

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.

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

标签: c++ cmake clion
1条回答
疯言疯语
2楼-- · 2019-07-16 13:10

You can use file(COPY idiom:

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

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)

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.

查看更多
登录 后发表回答