Nathaniel Barragan
Nathaniel Barragan

Posted on

Why isn't my file being compiled

Hello, all!
Has this ever happened to you? You're writing your program, and you try to compile it to even make sure the file you're working on compiles and it compiles perfectly fine. Then you try to actually use that file and suddenly it doesn't compile. What the heck! I wanted to check for this earlier. Well you've fallen victim to one of the best parts about Zig's compiler, lazy compilation.

What is lazy compilation?

Lazy compilation is the answer to a simple question, "Why am I compiling files I'm not even using?". The answer is simple. Don't. If a file is not included in any other file and used, why should I have it be included in the final binary? In fact, why should we look at it at all? This benefit comes from Zig's build system being integrated into the compiler. The compiler will know what files are actually being used and which aren't, giving the build system the information needed to know which files do and don't need to be compiled.

Well what if I don't want it to skip over its file?

You might be wondering why this is a relevant question. Why would you want a file if you aren't using the actual code. The answer to this is pretty simple, and it's that the file provides some sort of code that is called, but not by you explicitly. For example, if I need an entry point for a hobby kernel, this entry-point isn't explicitly called by the program, but it is still used!

This is pretty simple. There's a pattern in zig that takes care of exactly this:

comptime {
    _ = @include("file.zig");
Enter fullscreen mode Exit fullscreen mode

This is not the same as just simply

_ = @include("file.zig");
Enter fullscreen mode Exit fullscreen mode

because this file is still not being used, making it not needed to be compiled, but if you can prove that this file needs to be checked at compile-time (hence the tag for comptime), then the file will at least be looked through, and things will be parsed and compiled as needed.


This was just a simple look through a part of how Zig compiles your source tree. I hope this helps some people.

Oldest comments (1)

yanwenjiepy profile image

Yes, the compiler should be explicitly told to compile this file, just like the database-driven package in Go, we don't explicitly call any methods and functions in it, but we still have to explicitly declare that we want to import the package.