Search code examples
c++filecompile-time

Write to a file at compile time in C++?


I was doing some C++ metaprogramming, and I had the following code:

main.cpp

#include <fstream>

int main() {
    // not allowed
    constexpr {
        ofstream foo("foo.asm");
        foo << "incq   %rax\n";
        foo.close();
    }

    __asm(
        #include "foo.asm"
    );
}

foo.asm

        movw   $255, %ax
        movw   $1137, %bx
        addb   %bl, %al\n
        adcb   %bh, %ah

Is it possible to write to this file at compile-time?


Solution

  • No.

    However, most build systems will allow you to execute any code you want right before they compile the file, it's not really meta-programming but it might solve your issue.