1

I have a source input file

long content to be included

And want to include it and handle as a string

const char* mydata = 
#include "myfile.txt"
;

I need to make the content becomes raw string as

R"(long content to be included)"
5
  • 1
    Write R"( to the header file. Append the contents of the input file. Append "). I think CMake have functionality to do all of that built-in, you might want to read its documentation. Otherwise you can invoke external OS-specific commands to do it (for example on POSIX systems like Linux or macOS you can use echo and cat). If you use the external solution, I recommend you create a simple script which does it all, and invoke that from CMake. Now you try, and tell us how your attempt worked or not. Commented Oct 13, 2023 at 11:11
  • This seems like an XY problem. If you want the contents of arbitrary files to show up in your binary you can just do it using the linker. Here is an answer that uses CMake to do so. Commented Oct 13, 2023 at 11:28
  • 1
    CMake .in files are the way I've seen to do this, but I have unfortunately never setup a .in file. Hoping the search term at least helps. Commented Oct 13, 2023 at 11:31
  • 2
    Alternatively, you can use CMake's configure_file with the @ONLY option to fill in the file from a template. Commented Oct 13, 2023 at 11:32
  • @Someprogrammerdude Botje and John . Thanks for all your suggestions, I found a way with configure_file. Commented Oct 13, 2023 at 11:46

1 Answer 1

3

Thanks for your suggestions. I find a solution for my problem with configure_file api.

#include <iostream>
#include <stdio.h>
#include <string>

const char *test_data = R"(
@FILE_CONTENT@
)";
int main() { printf("%s\n", test_data); }
file(READ resources/data.txt FILE_CONTENT)
configure_file(test.cpp.in test.cpp @ONLY)
Sign up to request clarification or add additional context in comments.

2 Comments

I think this won't add a build dependency on resources/data.txt so if you change that file and rebuild it won't update properly.
I think this is the solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.