Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refer to a C symbol from Zig which is a keyword?

Tags:

c

zig

I want to call the error(3) function from Zig.

I can do this by defining a new symbol with a name that is not a Zig keyword:

@cInclude("error.h");
@cDefine("_error", "error");

Is this the recommended way to do this, or is there a different way to get at the name error, as c.error obviously doesn't work?

like image 943
Reuben Thomas Avatar asked Nov 27 '25 12:11

Reuben Thomas


1 Answers

Quote from Identifiers

Identifiers [...] must not overlap with any keywords. [...] If a name that does not fit these requirements is needed, [...] the @"" syntax may be used.

// example.zig
// run with `zig run example.zig -lc`

const c = @cImport({                                                                                
    @cInclude("error.h");                                                                           
});                                                                                                 
                                                                                                    
pub fn main() !void {
    // Names inside `@"` `"` are always recognised as identifiers.                                                                               
    _ = c.@"error"(0, 0, "this uses @\"error\"\n");                                                 
}

You can also assign c.@"error" to a new function c_error or use @cDefine("_error", "error"); like you did:

// alternatives.zig
// run with `zig run alternatives.zig -lc`

const c = @cImport({
    @cInclude("error.h");
    @cDefine("_error", "error");
});

const c_error = c.@"error";

pub fn main() !void {
    _ = c._error(0, 0, "this uses _error\n");
    _ = c_error(0, 0, "this uses c_error()\n");
}
like image 69
hdorio Avatar answered Nov 30 '25 06:11

hdorio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!