On Monday, 15 October 2012 at 13:11:29 UTC, bearophile wrote:
Adam D. Ruppe:

You could just version it:

version(foo_main)
void main() {}

That's not good enough.

What I as talking about is: when the D compilers know a module is
the main module, it defines a _standard_ version boolean flag,
named like "is_main_module" as true. And it gives a compiler
error if it can't find a main. Otherwise "is_main_module" is
false.

It's meant to be used as:


module modulea;
int foo() { return 0; }
static if (is_main_module) {
   unittest {}
   void main() { // demo code
     import std.stdio;
     writeln(foo());
   }
}



module moduleb;
import modulea;
int bar() { return 1; }
static if (is_main_module) {
   unittest {}
   void main() { // demo code
     import std.stdio;
     writeln(foo());
     writeln(bar());
   }
}


When you compile modulea, defines its is_main_module as true, it
runs its unittests (if you have used -unittest), and its main,
that is a demo for the A module.

If you compile the moduleb (with rdmd or something), it knows
moduleb has to contain the main, it defines is_main_module=true
in moduleb and defines is_main_module=false for modulea. So it
compiles the main of moduleb and ignores the main of modulea. So
it runs the demo code for moduleb only.

Using a non-standard user-defined version as you suggest misses
all this, and it's not good enough. Standardization and
automation is important here.

Bye,
bearophile

I'm sorry to say but that *is* a _horrible_ _hack_. It looks almost as awful as it does in python with the underscores.

Java has the correct DRY solution - each class can define a static main method but the compiler only uses the one specified by a compiler switch. The above basically asks the programmer to endlessly repeat the same trivial implementation boilerplate that should be written just once _in_ the compiler.

Reply via email to