Search code examples
attributesdprogram-entry-pointweakscriptedmain

Is there a way to override a module's main function in the D programming language?


If you really need to, you can specify __attribute__((weak)) in C (see scriptedmain). This allows a program to double as API and executable, allowing code that imports the API to overwrite the main function.

Does D have a way to do this? Python has if __name__=="__main__": main(), but the weak syntax in C seems much closer.


Solution

  • Yes, using version directives, which require special options to rdmd and dmd.

    scriptedmain.d:

    #!/usr/bin/env rdmd -version=scriptedmain
    
    module scriptedmain;
    
    import std.stdio;
    
    int meaningOfLife() {
        return 42;
    }
    
    version (scriptedmain) {
        void main(string[] args) {
            writeln("Main: The meaning of life is ", meaningOfLife());
        }
    }
    

    test.d:

    #!/usr/bin/env rdmd -version=test
    
    import scriptedmain;
    import std.stdio;
    
    version (test) {
        void main(string[] args) {
            writeln("Test: The meaning of life is ", meaningOfLife());
        }
    }
    

    Example:

    $ ./scriptedmain.d
    Main: The meaning of life is 42
    $ ./test.d
    Test: The meaning of life is 42
    $ dmd scriptedmain.d -version=scriptedmain
    $ ./scriptedmain
    Main: The meaning of life is 42
    $ dmd test.d scriptedmain.d -version=test
    $ ./test
    Test: The meaning of life is 42
    

    Also posted on RosettaCode.