mcandre
mcandre

Reputation: 24642

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.

Upvotes: 4

Views: 146

Answers (3)

BCS
BCS

Reputation: 78633

IIRC there is a way to get code to compile to a library rather than an object file. Because of the way the linker searches for things, you can use that to get the same effect; just put the target with the main you want to use first in the link order.

Upvotes: 0

mcandre
mcandre

Reputation: 24642

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.

Upvotes: 6

Vladimir Panteleev
Vladimir Panteleev

Reputation: 25187

I believe __attribute__((weak)) is a GNU extension which emits special linker instructions for weak linking, so it's very toolchain-specific. There is nothing in DMD for this AFAIK, but other D compilers (GDC or LDC) may support their backends' extensions.

Upvotes: 2

Related Questions