3

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?

Reuben Thomas
  • 647
  • 6
  • 13

1 Answers1

3

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");
}
hdorio
  • 12,902
  • 5
  • 34
  • 34