Home > Net >  Using `syscall.LINUX_REBOOT_CMD_POWER_OFF` when programming on windows for linux
Using `syscall.LINUX_REBOOT_CMD_POWER_OFF` when programming on windows for linux

Time:05-01

I'm developing code using Golang on windows as it is easier for testing purposes, but the final bin should run on a raspberry pi.

I need to call syscall.Reboot(syscall.LINUX_REBOOT_CMD_POWER_OFF) which works fine however, I need to comment it out on windows to test the binary and uncomment it when building in on the rpi. Even if I test the os to determine if the function is called, since it does not seem to exist on windows, go won't build it. Is there a way to build the code on windows even though this function doesn't exist?

I do not wish to do any code edits on the rpi, and i cannot use the wsl i need to communicate with usb devices and such which is easier when building on the native os

CodePudding user response:

It sounds like you want conditional compilation as described here:

https://blog.ralch.com/articles/golang-conditional-compilation/

You could have two source files in your package that use the _os nomenclature as the name. Both files export a function that does the appropriate behavior.

reboot_linux.go

package main

import "syscall"

func Reboot() {
    syscall.Reboot(syscall.LINUX_REBOOT_CMD_POWER_OFF)
}

reboot_windows.go

package main

import "fmt"

func Reboot() {
    fmt.Println("A reboot would have occurred")
}

When you do go build it won't compile reboot_linux.go on Windows. Nor will it compile reboot_windows.go on Linux.

Interestingly enough - this is exactly how Go separates out the implementations of the syscall package in its own source code.

  • Related