有没有办法在D编程语言中覆盖模块的主要功能?

mca*_*dre 4 attributes program-entry-point d weak scriptedmain

如果确实需要,可以__attribute__((weak))在C中指定(参见scriptedmain).这允许程序兼作API和可执行文件,允许导入API的代码覆盖主函数.

D有办法做到这一点吗?Python有if __name__=="__main__": main(),但weakC中的语法似乎更接近.

mca*_*dre 6

是的,使用版本指令,这需要rdmd和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());
    }
}
Run Code Online (Sandbox Code Playgroud)

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

例:

$ ./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
Run Code Online (Sandbox Code Playgroud)

还发布在RosettaCode上.

  • 从技术上讲,你并没有覆盖main,而是使用条件编译.它更接近于`#ifdef`然后更接近`__attribute__`. (2认同)