I have discussed this is little problem about three years ago; in the meantime 
the situation is changed (rdmd has appeared, DMD has grown the -deps switch, 
etc).

I have a little module named "modu":

module modu;
import std.stdio;
int foo() {
    return 0;
}
int main() {
    writeln("modu.main");
    return 1;
}


I create a second module named "somemodule", and import just the foo() function 
from mod:

module somemodule;
import std.stdio;
import modu: foo;
int main() {
    writeln("somemodule.main");
    return foo();
}

Now if I compile somemodule normally, with:

rdmd somemodule.d

I receive an error like:

OPTLINK (R) for Win32  Release 8.00.12
Copyright (C) Digital Mars 1989-2010  All rights reserved.
http://www.digitalmars.com/ctg/optlink.html
...   Offset 00137H Record Type 00C3 
 Error 1: Previous Definition Different : __Dmain
--- errorlevel 1


To avoid this problem in Python there is a common idiom:

if __name__ == '__main__':
    # main code here...
    

This idiom allows to define and run a "main" only for the main module. 
Currently in D there is no notion of "main module", but I see a simple way to 
avoid this problem in D too, defining a new standard version name that tools 
like rdmd, bud, etc define for just the first module (like for the only module 
name given to rdmd), and don't define for all other modules found and compiled 
recursively:

module mod;
int foo() {
    return 0;
}
version (main_module) int main() {
    return 1;
}


The usage of main_module is optional.

I like to keep a main() in most modules, even the ones that are usually not 
supposed to be the main modules of a program, because I put in their main() 
some demo code that shows what this module does (and a main is useful to run 
unittests too, rdmd has the --main switch for this). Most of my Python modules 
have such demo main code, that runs only if you run them as main modules.

Bye,
bearophile

Reply via email to