DMD Refuses to Compile Multiple Source Files

Mike Parker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jan 18 15:12:15 PST 2017


On Wednesday, 18 January 2017 at 19:28:20 UTC, Samwise wrote:

> Alright, so I misunderstood what ketmar was saying. His 
> solution did work. I'm just not sure I understand what you are 
> trying to say here:
>
>> But really, the proper thing to do is to drop the prototype 
>> and import the module with the implementation.
>
> This will still preserve my multiple source files, without 
> worrying about the headers, right? Thanks,
> ~Sam

First, let's get some terminology straightened out. This:

int getReturnCode();

is not a "header". It's a function declaration (or function 
prototype). Both C and C++ are sensitive to the location of 
declarations and implementations, i.e. you can't call a function 
or use a type unless it has been declared or implemented before 
the point at which it is called:

```
// Error! funcA is used before it is declared
void funcB() { funcA(); }
void funcA() { ... }
```

The example can be fixed by either moving the implementation of 
funcA above the implementation of funkB, or adding a prototype of 
funcA above funkB:

```
void funcA();
void funcB() { funcA(); }
void funcA() { ... }
```
In C and C++, a "header" is a file that is used to collect 
publicly usable type and function declarations in one place. This 
saves the work of declaring them in every source file that needs 
them.

D was designed with a module system to avoid the need for 
function prototypes and header files. You can still use them, as 
they are handy when interfacing with C and C++ programs, but they 
are not required. D is also not sensitive to the location of type 
and function implementations. The first example above would not 
be an error in D. You can implement a function before or after 
its point of use.

So the D way is to forego the use of function prototypes 
entirely. You implement your functions and types in modules 
(source files), then use the import statement to make the 
declarations in other modules.

So your initial example becomes:

```
// main.d
import std.stdio;
import returncode;

int main() {
	writeln("Hello World!");
	return getReturnCode();
}

// returncode.d
module returncode;
int getReturnCode() { return 4; }
```


More information about the Digitalmars-d-learn mailing list