Compiling multiple source files --- each file separately, or all together?

H. S. Teoh hsteoh at qfbox.info
Fri Dec 26 16:33:14 UTC 2025


On Fri, Dec 26, 2025 at 10:44:21AM +0000, David Given via Digitalmars-d wrote:
> When compiling C or C++, and you have multiple source files, you
> typically compile each source file independently into a .o file and
> then link them together. This is either done manually in the build
> script or automatically if you pass multiple source files into the
> compiler program.
> 
> When compiling D, and I do this:
> 
> ldmd2 a.d b.d c.d d.d -o program
> 
> ...it's unclear to me whether it's doing the same as C/C++ does, and
> compiling each file individually, or whether it's compiling all the .d
> files together using a single compiler instance. I _think_ it's
> compiling them together (and then invoking the linker as its own
> stage). Can anyone confirm/deny this? If it's true, is this true for
> all dmd-like D compilers?

The D compiler compiles all source files together. In some cases it's
able to optimize across files when compiled this way, as opposed to when
compiled separately (but not necessarily so; imported files will still
be parsed and analysed, just some parts of codegen may not run when the
imported file isn't listed on the command-line).

This applies to all D compilers.


> Context: working on D support for a build tool, and it makes a big
> difference to how my tooling would work.
[...]

The general recommendation in D is:

1) For small projects (say up to 25-30 source files or so -- the exact
number depends on how much memory you have, as D compilers generally are
big memory hogs, so go as high as you can without running into OOM
issues), just compile everything in one go with `-i`, like so:

	dmd -i main.d -ofprogram

2) For large projects with multiple packages (i.e., package
subdirectories), compile each package separately with `-i` then link
everything together at the end:

	objs=""
	for pkg in pkg1 pkg2 pkg3 ... ; do
		dmd -i ${pkg}/*.d -of${pkg}.o
		objs="$objs ${pkg}.o"
	done
	dmd $objs -ofprogram

The same applies to compilations with ldc2, gdc, etc..


T

-- 
Did you hear about the kidnapping at school today?  Everything's OK now -- he woke up.


More information about the Digitalmars-d mailing list