yeomandev
yeomandev

Reputation: 11796

How to import a class from a different source file in D?

I am new to the D language. I am attempting to import my custom class for use in the main() function.

Project struture:

DlangApp/app.d
DlangApp/ClassOne.d

ClassOne.d:

import std.stdio;

class ClassOne
{
    string firstName;
    string lastName;

    this(string first, string last)
    {
        firstName = first;
        lastName = last;
    }

    void writeName()
    {
        writefln("The name is: %s %s", firstName, lastName);
    }
}

app.d:

import std.stdio;
import ClassOne;

void main()
{
    auto aNumber = 10;
    auto aString = "This is a string.";
    writefln("A string: %s\nA number: %s", aString, aNumber);
}

When I run dmd -run app.d, I get this error message:

app.obj(app)
 Error 42: Symbol Undefined _D8ClassOne12__ModuleInfoZ
---errorlevel 1

What am I doing wrong here?

Upvotes: 4

Views: 382

Answers (2)

Michal Minich
Michal Minich

Reputation: 2657

You can compile using rdmd. It is a wrapper around dmd with some additional functionality, but you can still pas dmd arguments. The main benefit is that you need to specify only one .d file - the one with main function. It understands import directives so it will include all necessary .d files

Upvotes: 3

DejanLekic
DejanLekic

Reputation: 19797

Execute dmd -ofquakkels_app app.d ClassOne.d and, if the compilation was successfull, you will get the quakkels_app executable.

Or, if you really want to use the -run <file> [args...] parameter: dmd ClassOne.d -run app.d . Note that I put -run at the end - because after -run filename you may want to put some parameters that you want to pass to your application.

Now you probably understand why you got the compilation error above - simply DMD did not compile ClassOne.d file...

Upvotes: 5

Related Questions