How to compile and use an external class
Derek Parnell
derek at psych.ward
Tue Dec 2 02:06:46 PST 2008
On Tue, 2 Dec 2008 09:28:53 +0000 (UTC), Some Guy wrote:
> I am busy learning D and I want to be able to use classes now. I am
> used to programming in C# where it does everything for you and you
> don't have to think about this kind of thing so I now have no idea
> how to compile a program from the command line that uses a class in
> another source file.
>
> I have a source file called MyProgram.d which contains the main
> program and I have a file called MyClass.d that contains a class
> called MyClass. I want to be able to create an instance of MyClass in
> the main program but I don't know what to type to compile it the
> command line. This is what I have tried so far which doesn't work:
>
> dmd MyProgram.d MyClass.d
>
> Thanks in advance for your help.
Seeing that you didn't show us your code, I took the liberty of writing
some example code...
---------- myprogram.d ---------
module myprogram;
// Tell the compiler that this file needs to know
// about what is in the file 'myclass.d'
import myclass;
import std.stdio; // Need this to use writefln();
void main()
{
// Create an instance of the class.
MyClass inst = new MyClass();
// Invoke a method in the instance.
writefln("First %s", inst.A_Method());
// Create another instance of the class.
MyClass yai = new MyClass(5);
// Invoke a method in the instance.
writefln("Second %s", yai.A_Method());
}
--------- end of file -------------
---------- myclass.d ---------
module myclass;
class MyClass
{
int SomeAttribute;
// A class constructor
this()
{
SomeAttribute = 1;
}
// Another class constructor
this(int InitData)
{
SomeAttribute = InitData;
}
// A method
int A_Method()
{
return SomeAttribute;
}
}
--------- end of file -------------
The line to compile these ...
dmd myprogram myclass
When running the program 'myprogram' you should get ...
c:\>myprogram
First 1
Second 5
--
Derek Parnell
Melbourne, Australia
skype: derek.j.parnell
More information about the Digitalmars-d-learn
mailing list