0

file1.cc

void func() {
  std::cout << "test\n";
}

file2.cc

...
std::string str = GET_FILE("file1.cc");
...

So, what I need is that str has the content of file1.cc as string, in compile time, NOT execution time.

How to implement this GET_FILE macro?

Alex
  • 3,301
  • 4
  • 29
  • 43
  • It's impossible. A good alternative is to use `objdump` to put `file1.cc` into an object file and then link with it, as described here: https://balau82.wordpress.com/2012/02/19/linking-a-binary-blob-with-gcc/. You'll have a pointer to the data at linking time, but it's impossible to construct `std::string` from it at compilation time. – HolyBlackCat Jul 31 '18 at 16:44
  • You can #include the file with a macro to convert it to a const char* – nitronoid Jul 31 '18 at 16:45
  • @nitronoid It wouldn't work. – HolyBlackCat Jul 31 '18 at 16:45
  • @HolyBlackCat, it isn't possible, if GET_FILE generates a literal string token "asdf", it could be possible. – Alex Jul 31 '18 at 16:46
  • @HolyBlackCat #define STR_SOURCE(...) #__VA_ARGS__ ... std::string t = STR_SOURCE(int func() {return 3;}) – Alex Jul 31 '18 at 16:48
  • You could try `std::string t = STR_SOURCE( #include "file1.cc" )` (make sure the `#include "..."` is on a separate line), but I doubt it would work. – HolyBlackCat Jul 31 '18 at 16:50
  • @HolyBlackCat , no, It doesn't work. It was only an example, that is possible generate data to std::string on compile time – Alex Jul 31 '18 at 16:51
  • @Alex Unless the compiler performs some tricky optimizations, the string will be constructed at runtime, when the program starts. Not at compilation time. – HolyBlackCat Jul 31 '18 at 16:59
  • Have you tried the macro `__FILE__`? On some platforms or compiler tool sets, the macro will expand to the file name including the path (absolute file name). Check your compiler macros to see if there is a macro that only returns the base filename (without the path). Since this is a preprocessor macro, the value is known at compile time. – Thomas Matthews Jul 31 '18 at 17:26

0 Answers0