How to change the path of the file to be created in cmake?

Viewed 129

I'm using CMake to build the code. It creates a subdirectory src/a.out and stores the output file. Until now I'm defining the path manually if I want to store the created file some place else e.g., like this

std::ofstream ofile;
ofile.open("/home/results/foo.txt");

I'd like to know is there a way I can define the path in CMake rather than in code?

1 Answers

One solution is to pass the path through compiler arguments.

project( test )
cmake_minimum_required( VERSION 3.0 )
add_executable( testparm testparm.cpp )
target_compile_options( testparm PUBLIC -DMYPATH=/tmp/file.txt )

In testparm.cpp

#include <fstream>
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
int main() {
        const char* path = TOSTRING(MYPATH);
        std::ofstream file( path );
        file << "Hello World\n";
        return 0;
}

Running:

$ strace ./testparm
...
openat(AT_FDCWD, "/tmp/file.txt", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3
write(3, "Hello World\n", 12)           = 12
close(3)                                = 0
exit_group(0)    
Related