Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set cmake, in order to add txt files into working directory as resource?

Tags:

c++

cmake

clion

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?

like image 411
TrW236 Avatar asked Oct 29 '17 00:10

TrW236


1 Answers

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.

like image 194
Cinder Biscuits Avatar answered Nov 01 '22 06:11

Cinder Biscuits