No -c no main()

bearophile bearophileHUGS at lycos.com
Fri Mar 20 05:23:12 PDT 2009


Ary Borenszweig:
> It is useful. Suppose you are writing a new module and want to test 
> something quickly (not with unittests, maybe make a little program to 
> see how a specific feature you just wrote works). So you write a main 
> right there in the module, compile it and link it saying that the main 
> is in your new module. And you can then run it.

It has many usages, we have already discussed about this in the past.
In D you can group related functions and classes into one module, so sometimes a module can be run alone (with the help of some modules it imports). So you can add demonstration code into its main, or benchmark/testing code, or module testing code, and so on. You can even create a program where certain modules can be sub-programs, that you can run alone to do specific sub-purposes, instead of using them as imported modules.
Such usages are very common in Python too, there's even a idiomatic syntax to do such things. In the past other people and me have suggested some ways to do this.
One of them was to add a __MAIN__ compile time constant defined as false for all the modules that the compiler is asked to not compile as the (main) module that contains the main(), so you can use a:
static if (__MAIN__) { void main(string[] args) {...} }
to wrap the main function. I don't remember if this very simple idea was already shot down or improved by better ideas.

Bye,
bearophile



More information about the Digitalmars-d mailing list