Hyrbid Modul and program behavior for source file D

The Python source file has the good property of being able to act both as a module and as a standalone program (tool) using a template

if __name__ == "__main__": 

Is it possible to get the same behavior for the source file of the D-module?

+4
source share
3 answers

(Unix only)

You can use the shebang line, which sets version , which includes the main function:

 #!/path/to/rdmd --shebang -version=run version(run) void main() {} 

Make an executable file ( chmod +x foo.d ) and run it as a program ( ./foo.d ).

Be sure to use a unique version identifier (as opposed to what I did here). Maybe includes the full name of the module in one form or another or use the UUID.

+6
source

It depends on what you are trying to do. Program D requires only one main function for all modules as an entry point, so there is no implicit way, as in Python. Path D is to create the executable as a separate module that contains main and imports another module.

But if you just want to do this for testing, you have to put the executable code in unittest blocks (without main ), and then you can run the file with rdmd -main -unittest scratch.d , which will add stub main for you.

If you really want to make a module with a dual purpose (which is not a D Way), you can put main in a unique version block:

 module scratch; // file scratch.d import std.stdio; void foo(){ writeln("FOO"); } version(scratchExe) { void main() { foo(); } } 

Then compile the executable version with dmd scratch.d -version=scratchExe .

+5
source

yes with pragma:

 void foo(){ //... } version(fooMain){ pragma(startaddress, foo); } 
+4
source

Source: https://habr.com/ru/post/1499838/


All Articles