We are working on a c++ project using CMake. In the project we are referencing some resource files like resources/file.txt
(located directly inside the project folder) using the std::ifstream
class. 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).
How can I set up CMake or Visual Studio so I can reference these files without changing their paths? I am still a pretty big novice using CMake but I didn't find anything that worked.
EDIT:
Minimal code showing the issue:
#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;
}
This program should load the "Test_File.txt" located inside the src folder with the folder structure being:
- src
- main.cpp
- CMakeList.txt
- Test_File.txt
- CMakeList.txt
The problem here is that the program cannot find the Text_File.txt while the other team members don't have such issue. Absolute paths of course work but they are obviously not the way to go.
I've already tried to set the working directory using the
VS_DEBUGGER_WORKING_DIRECTORY
parameter with set_target_properties(${PROJECT_NAME} PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
after add_executable(${PROJECT_NAME} "${CMAKE_CURRENT_SOURCE_DIR}/main.cpp")
but that does not seem to work either.