#Writing code that only compiles on certain build targets

1 messages · Page 1 of 1 (latest)

stoic cove
#

Hi!

In C if I wanted to define functions/structs/etc. that have different implementations depending on what operating system the build was targeting I could do something like this

/// my_code.h
int do_platform_specific_function();

/// my_code_win32.c
#if defined(_WIN32)
#include "my_code.h"
#include <Windows.h>

// only compiles on windows
int do_platform_specific_function() { ... }
#endif

/// main.c
#include "my_code.h"

int main() {
  // calls based on OS-specific C file got compiled
  int value = do_platform_specific_function();
  ...
}

where do_platform_specific_function() can have platform-specific implementations and the code that uses it doesn't have to care about the details. Also with the benefit that code which links to OS-specific libraries won't get compiled on other OSes (and thus not causing linking errors). How can I achieve something similar in Zig? I couldn't find much clear information online about this.

ocean tinsel
#

const builtin = @import("builtin")
from there you can switch or if various fields of that struct and ittl be evaluated at comptime

stoic cove
#

can I do something similar for functions? e.g. if I have some function that links against win32 libs that I wouldn't wanna try link against in Linux, would I be able to define functions such that it only happens in a certain os?

rare forge
stoic cove
#

so if I had something like

fn win32_func() void {
  // calls some windows api libs; would produce linker error in linux
}

fn linux_func() void {
  // calls some linux api func; would produce linker error in windows
}

fn do_something() void {
  switch (builtin.os.tag) {
    .windows => {
      win32_func();
    },
    .linux => {
      linux_func();
    },
  }
}

the compiler would automatically optimize this such that, if I was compiling for windows, linux_func would simply never get compiled and thus no linker errors would produce? and vice versa if I was targeting linux

#

just to make sure Im interpreting your claim correctly

tribal hamlet
#

yeah, that's right

#

though it's not an "optimisation"

#

it's a semantic guarantee

stoic cove
#

ah

#

either way, does exactly what I wanted 👍 ty all for the help