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?
You can use
file(COPY
idiom:But may I also suggest
configure_file
with theCOPYONLY
option. In this way, whentest.txt
is modified, CMake will reconfigure and regenerate the build. If you don't need that, just usefile(COPY
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:I think in your case, the first example is most appropriate, but now you have tools in your toolbox for all scenarios.