Is there a way to conditionally add cDefines within cImport?

I’m looking to do something like this within a cImport, which doesn’t work:

    if (builtin.mode == .Debug) {
        @cDefine("SANITIZE", {});
    }

Shortly after posting this I figured out I could accomplish this by using addTranslateC and defineCMacro using the build system.

2 Likes

The syntax is:

const c = @cImport({
    if (builtin.mode == .Debug) {
        @cDefine("SANITIZE", {});
    }
});

See also:

Welcome to ziggit :slight_smile:

1 Like

That’s what I was doing. It compiles, but doesn’t actually work.

A working example:

❯ cat foo.h
#include <stdio.h>

#ifdef SANITIZE

void foo()
{
    printf("SANITIZE\n");
}

#else

void foo()
{
    printf("nop\n");
}

#endif

❯ cat test.zig
const builtin = @import("builtin");

const c = @cImport({
    if (builtin.mode == .Debug) {
        @cDefine("SANITIZE", {});
    }
    @cInclude("foo.h");
});

pub fn main() void {
    c.foo();
}

❯ zig run test.zig -I . -lc
SANITIZE
2 Likes

Ah, thanks. Looks like my problem was when I was inspecting the generated source, zls was resolving to a previous version, not the latest version.

1 Like