302 points · by jstrieb · 2y ago · 136 comments
What's happening is that C imports are moving to the build system, instead of being a compiler builtin. It's part of making LLVM and libclang optional for programs which don't use it, but the use case of building C programs, and integrating C libraries with Zig programs, remains a central design goal.
The build system is relatively new, and a lot of things which were originally independent subcommands are being consolidated into the build system.
There's a sort of ambient impression that "Zig won't support C anymore" floating around, I'm not sure from your post whether you have that impression or not, but it isn't even vaguely true.
It just means that importing C libraries will be a build step, and not something you write directly into the relevant source code. This is not a big deal.
It 100% is a big deal. I explained this in another comment [0].
The idea that C programmers, C programmers, are going to start bailing en masse out of the top of the Zig funnel, because they have to copy-paste a build.zig gist to get started? This is risible.
The complexity has moved to a slightly different place. That's it.
const win32 = @cImport({
@cInclude("windows.h");
@cInclude("winuser.h");
});
You will write: const win32 = @import("win32");
Where the module "win32" is declared in build.zig.So `zig cc` will have to go as well ? I was under the impression Zig as a drop-in C (cross-)compiler was one of its main selling points.
The ability to seamlessly compile C/C++/ObjC code within a Zig project is extremely important for me as well, but I'm fine with that job being delegated to a Zig package and the Zig build system.
One of the main reasons I took Zig seriously was their C interop story—as someone who loves C and dislikes almost every implementation of C interop and FFI I’ve used in other languages (Rust is a notable exception to this), I was pretty much sold on Zig when I was able to, in a total of < 3-ish hours, (1) implement a complete Zig wrapper over a C library I wrote without introducing any overhead, (2) build a Zig program using the wrapper, and (3) cross-compile the program, statically, producing single binaries for 5 different targets…Linux (amd64, arm64), macOS (amd64, arm64), and Windows (amd64), ALL from one laptop using a single Zig executable and some simple flags. This was C interop and productivity I’ve never experienced before.
I respect Andrew a lot (I think he’s pretty brilliant), so I hope this turns out to not be as bad as I think it’ll be for those of us who love Zig for what brings to the table for programmers who are biased toward C.
https://github.com/ziglang/zig/issues/16270#issuecomment-161... https://github.com/ziglang/zig/issues/16270#issuecomment-161...
> This is not the first controversial change I have made to the Zig project, and it won't be the last. I have a vision, and I know how to execute it. People are often surprised by what Zig has accomplished, and they wonder why other projects have not done what Zig does. Well, you are seeing the magic right now. I ignore the peanut gallery and do what I know is right, while taking care of my users' needs at the same time. If you don't understand now, you will understand once this plan unfolds. By that time it will seem obvious in hindsight.
He's probably brillant and all but this ... feels like hubris.
What he should have done is announce a project at the same time that will maintain the current developer experience, even if that project is not part of the zig foundation. The developer doesn't care about how he builds zig. They want 1) download 2) use. It doesn't matter from where. If today it's directly from zig, and tomorrow it's from elsewhere to download a combined package, that 's all the devs needed to hear.
Have you tried D? It can import C files as if they were D modules: https://dlang.org/spec/importc.html
Basically, if there's a `hello.c` file next to your D file, you simply import it with:
import hello
And use the functions it provides. You can also import only a subset of it, of course: import hello: square;
Or rename the import: import hi = hello;
The C stdlib is exposed by D's stdlib as if it were a D library: https://dlang.org/phobos/core_stdc_assert_.htmlC libraries (header files) can be compiled to D and then used as D modules as well, see https://github.com/jacob-carlborg/dstep
Is that as good as Rust?
I tried D years ago (at least 5 years ago, I think), but I don’t remember experimenting with the C interop.
Your explanation sounds intriguing though. And a couple pretty smart folks I respect have talked about D too. So thanks for bringing it up. I’m going to make some time to experiment with it again some time soon.
> Is that as good as Rust?
Franky, although I don’t have firsthand experience with D, your explanation and example make the D C interop experience sound actually better than Rust’s. It seems more similar to Zig.
With hindsight, it is strange that the C community, with all the people and money behind it (and what scale!) never even managed to build a proper packaging manager (okay, there's now Conan, but that came from Python guys).
But then, there even still isn't a perfect C string library around (something that would combine GLib, SDS, ICU, say, and then standardize it in C2038).
[1] Hanson's C: Interfaces & Implementations (CII) - Str: https://cii.s3.amazonaws.com/book/pdf/quickref.pdf
[2] ICU - https://icu.unicode.org
[3] SDS - https://github.com/antirez/sds
[4] GLib - https://docs.gtk.org/glib/struct.String.html
Package managers are a lot more complex than people realize. Every attempt I've seen in every language has significant lacks for common real world cases.
Most commonly they assume all the world is their language. Very commonly they want to take over all package management but don't have a good easy story for working with the OS package manager (I know Windows doesn't really have a package manager - but you still need to interoperate with it!). Those are big issues anyone in a complex project will face in the real world, there are also lots of little warts that will bite you.
Yes package managers are nice on your trival project. However they all get in the way in your non-complex project - some more than others.
The actual build system functionality is 'just' an extension to the stdlib.
It can compile almost any dependency on demand, even doing cross-compilation. And it's used by at least Microsoft and Google.
This does not seem bad in paper. One thing that does worsen with this is that in @cImport you could also comptime define preprocessor macros which was really cool, now that would have to be handled by build.zig I guess.
I’ve been able to convince C programmers to try out and use Zig just due to this unique ability alone, and to be clear, getting C programmers to seriously consider any language other than C is generally very difficult!
Having to consider another build system (with its own semantics), which the current Zig experience doesn’t require, changes the experience much more substantially than I think the Zig team realizes.
I think that's an acceptable compromise.
Especially for C libraries which require configuration via preprocessor defines or compilation flags, the build.zig way is a lot cleaner than the @-builtins that are currently used (IMHO).
You’re oversimplifying what’s actually a significant change.
Right now, I can do the following:
1. Download a prebuilt Zig release [0], on a fresh computer (zero prerequisites).
2. Implement a C library foo via foo.h and foo.c.
3. Compile foo.c into an object file foo.o via `zig cc`, using standard GNU-compatible compiler flags, for virtually any of the common (and even not-so-common) compilation targets.
4. Implement a Zig program bar via bar.zig.
5. Directly import foo.h into bar.zig via `@cImport` and use the C API as if it was Zig code.
6. Compile bar.zig and foo.o into a statically-linked executable baz via `zig build-exe`, for virtually any of the common (and even not-so-common) compilation targets.
No knowledge of the Zig build system and its semantics necessary. This is one of the most attractive aspects of Zig for a C programmer. I’ve gone through these exact steps with C programmers who thought Zig seemed interesting in theory but just didn’t want to have to learn a new ecosystem, build system, etc. The moment I showed them how quickly they could get up and running with Zig (and test it out with C code), without even having to install anything, it suddenly was impressive enough to experiment with.
The build system requirement may seem minor if you’re already a Zig programmer, but it’s massive if you want to attract C systems programmers.
As it is currently described, @import of C will require build.zig and specific configuration therein.
For instance Odin allows to define a 'link_prefix' for C APIs which is then stripped from the imported symbols:
@(default_calling_convention="c", link_prefix="sg_")
This causes name transformations like: sg_setup() => setup()
sg_shutdown() => shutdown()
...maybe even convert from common case-conventions (like snake-, camel-, pascal- case etc...) to Zig's naming convention so that imported C interfaces don't look so alien relative to native Zig interfaces.> As a consolation prize, the TranslateC build step can be enhanced with advanced settings, such as namespace stripping and validation of existing bindings. Since changes to this don't require changing the language, it's OK if the scope & complexity increase to some extent.
Unfortunately, we must not forget forget ABOMINATIONCase and NAMESPACED_PascalCase (we could also generalize this to any switch from one convention to another after the first word). I've found they usually are, in fact, identifiable and roundtrippable. I've found the following usually works (it fails for multi-word prefixes or non-leading exceptions, and of course single-word identifiers are ambiguous):
count and strip all leading, then trailing, symbols (in some languages this is not limited to underscore but said languages usually need special handling anyway)
for every chunk separated by underscore, space, or hyphen (this may be nothing):
if the chunk either has no uppercase or has no lowercase, simply use it as a word. Otherwise:
for every sliding-window pair of letters (c, d) in the chunk:
if c is uppercase:
if d is lowercase, or d is a digit and there is lowercase elsewhere:
start a new word before c
Then for the words-to-convention direction: space and kebab case don't have any good answer for affixes AFAIK. Otherwise, restore at least the leading underscores (trailing underscores are usually keyword-avoiding)
for snake and screaming case, be sure to prepend an underscore if the *result* would start with a digit
for camel variants, prepend an underscore to each *word* that starts with a digit. But if there were originally more than 1 leading underscores, use those instead for the first word. translateSpecialCaseNames(.{
.{ .src = "ABOMINATIONCase", .dst = "case" },
.{ .src = "NAMESPACED_PascalCase", .dst = "pascalCase" },
});
...in my own language bindings generator, being able to define such special case mappings is actually quite important, mainly for handling that situation where an automatic mapping would result in a reserved keyword. const win32 = @cImport({
@cInclude("windows.h");
@cInclude("winuser.h");
});
pub fn main() !void {
_ = win32.MessageBoxA(null, "world!", "Hello", 0);
}
Equivalent D: import windows, winuser;
void main() {
MessageBoxA(null, "world!", "Hello", 0);
}
In essence pared it down to the essentials. The compiler figures out the rest.Sometimes people ask for a special syntax for importing C files, but I like this simplicity so much better.
Naked imports are also annoying. Which import did that MessageBoxA come from? windows? or winuser? Is it in the language kernel?
Explicit is better than implicit. The utter pain for the code writer of four or five keystrokes here and there is not worth confounding the code reader.
> Which import did that MessageBoxA come from?
If it exists in two or more imports, the compiler will give an ambiguity error. To resolve the ambiguity error, qualify the call with the name of the import:
windows.MessageBoxA(null, "world!", "Hello", 0);
or, one can do this: import windows : MessageBoxA;
or this: import windows, winuser;
alias MessageBoxA = windows.MessageBoxA;
You can be as explicit as you like, and don't need to worry about ambiguity because the compiler will issue an error for that. It works the same way for D imports.I recently started a new project. zig-init provides you with a working build.zig file and two very minimal project files under /src, one of which is a hello world binary and the other is a hello world library.
> Also I've had a lot of issues getting editor integration to work correctly.
ZLS is not at the same level of what you would expect from a more mature language. For example by default it will not help you with anything related to comptime.
I highly recommend reading this fairly recent blog post by Loris Cro:
https://kristoff.it/blog/improving-your-zls-experience/
It explains how you set up your build.zig and ZLS (a few lines of configuration) in order to get much more help from ZLS. It will then perform the equivalent of what `cargo check` (Rust) does.
I think its fair criticism that as a beginner, you don't actually want to deal with build.zig or even understand it. You just want to write some code and run it and look at build.zig after you gained some familiarity with the language itself.
VSCode is great when it works, but in cases like these it quickly becomes obvious that it's a hodge-podge of tools glued together via extensions and command lines rather than a purpose-built IDE.
* https://marketplace.visualstudio.com/items?itemName=llvm-vs-...
If you use ZLS [0], make sure you’re always using the right version for the Zig version you have installed on your machine. In my experience, that fixes 90% of editor issues I’ve encountered using Zig (I don’t use Visual Studio Code though, so it’s possible your editor issues are related to the editor itself).
I just prefer using Zig on emacs with the built-in eglot LSP client. You just tell it where you installed ZLS (and it won't do magic to get it for you) and off you go. It's the same level of support as with VS Code. If you're not new to emacs, maybe consider that (otherwise emacs may be too much of a rabbit hole :)).
I really want to get started with Zig but I don't want to go back to the age of nano/edit.com for learning a new language. Zig is complex enough already.
You could hop on the Discord and get some help with your configuration if you'd like. All things Zig are somewhat underdocumented currently, that could use some polish for sure.
Nothing wrong with that, imo. It's hard to evolve a language without having the ability to make breaking changes. They're doing the right things, generally making the right calls, and taking their time building instead of rushing.
So there is nothing technically impossible about having the access to macro names as a compiler-specific extension, it's just that there is no much demand for it.
It's not probably reflected to the language because C++ fears reflection in general and hates macros in particular.
Macros aren't a particular case of reflection... And at least in the way they're done in C++, they're a big source of bugs / spaghetti.
But only wicked gods would banish us from paradise
Why do they fear our power?
Because evil is what they are.
fn stringFromMsg(umsg: c_int) [:0]const u8 {
@setEvalBranchQuota(1000000);
inline for (@typeInfo(win32).Struct.decls) |field| {
if (field.name.len >= 3 and std.mem.eql(u8, field.name[0..3], "WM_")) {
if (umsg == @field(win32, field.name)) {
return field.name;
}
}
}
unreachable; // umsg is not valid, programming mistake
}
godbolt: https://zig.godbolt.org/z/7b73aoosfIn zig-budoux, I also do comptime reflection on cImport struct to assert compile time that we won't produce broken runtime code
https://github.com/Cloudef/zig-budoux/blob/master/src/c.zig#...
IME there's is no difference in (optimized) code generation between an if-else chain, a switch or (like in your example) an unrolled for-loop with an if inside. All those high level constructs will be optimized into a single lookup table, or a combination of multiple lookup tables and binary search to select between those. Only if there are absolutely no consecutive ranges in the switch-set, a binary search without jump tables will be used.
But I also habitually run with jacked up contrast and nerfed brightness, so I make no claims that what works for me would be a good idea for anybody else.