No -c no main()

Georg Wrede georg.wrede at iki.fi
Fri Mar 20 10:10:33 PDT 2009


bearophile wrote:
> 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.

In a bigger project, this would result in quite a few main() functions, 
in several files. People tend to write them for debugging, and then 
forget to delete them.

> 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.

The other option would be to write the new mains in new files. This 
would not pollute the files for the Real Project. And with a naming 
convention (say, myfoomodule-test2-main.d but the real main file having 
the appname and no main part), it would then become easy to find, 
remove, or list all the "other" mains.

Also, having mymodule-main.d (and possibly mymodule-other-main.d) makes 
it possible to have an unlimited number of "mains", all without 
polluting the original mylib.

> Such usages are very common in Python too,
> there's even a idiomatic syntax to do such things.

That would go well with Python being interpreted, and "an easy" language.

> 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.

I'd change "all the modules that the compiler is asked to not compile
as the (main)"

to "all the modules that the compiler is not asked to compile as the 
(main)".


Let's say multiple mains become legal. Then this __MAIN__ idea would at 
least give the programmer a chance to "point it out" in source code, 
that this is "just an auxiliary main".



More information about the Digitalmars-d mailing list