2011-10-18 10 views

回答

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()); 
    } 
} 

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()); 
    } 
} 

實施例:

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

也公佈在RosettaCode

+2

從技術上講,你並不是重寫main,而是使用條件編譯。它更接近'#ifdef',然後更接近'__attribute__'。 – RedX

+0

@ratchetfreak酷!你可以使用包裝在版本語句中的'pragma(startaddress,foo)'獲得相同的結果,而不包含版本 –

+0

中的主要函數。請給出一個完整的例子。 – mcandre

2

我相信__attribute__((weak))是一個GNU擴展,它爲弱鏈接發出特殊的鏈接器指令,所以它非常適合工具鏈。 DMAI沒有這個AFAIK,但其他D編譯器(GDC或LDC)可以支持它們的後端擴展。

0

IIRC有一種方法可以將代碼編譯爲一個庫而不是一個目標文件。由於鏈接器搜索事物的方式,您可以使用它來獲得相同的效果;只需在鏈接順序中將目標與首先要使用的主要對象相關聯即可。

相關問題