Read file on compiler time.

Adam D. Ruppe via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu May 29 13:43:57 PDT 2014


On Thursday, 29 May 2014 at 20:38:30 UTC, Remo wrote:
> Now another question is it also possible to save/write string 
> at compile time?

Sort of, use

pragma(msg, "some string");

and it will be printed out when that code is compiled. Important 
that it is when the code is compiled, NOT when the code is 
executed at compile time. So

void foo() { pragma(msg, "here"); }

will say "here" even if you never call foo. So you can't use it 
to print stuff out inside CTFE loops, and you might need to 
shield it with version {} or static if() {} to suppress printing.

But you can use it to print a completed string or something and 
then redirect it to a file in your makefile to do something:

string myfunction() {
    string value;
    foreach(a; ["a", "b"]) value ~= a;
    return value;
}

pragma(msg, myfunction()); // would say "ab"

dmd yourfile.d 2>&1 > foo.txt # redirect all compiler output into 
foo.txt




If you find yourself wanting to print a lot, I say you should 
just use a regualr program that runs normally instead of CTFE. 
Since most the language works the same way, transitioning to and 
from regular execution and compile time execution is easy and 
generally doesn't need you to change most the code.


More information about the Digitalmars-d-learn mailing list