Using `syscall.LINUX_REBOOT_CMD_POWER_OFF` when programming on windows for linux

huangapple go评论101阅读模式
英文:

Using `syscall.LINUX_REBOOT_CMD_POWER_OFF` when programming on windows for linux

问题

我正在使用Golang在Windows上开发代码,因为这样更容易进行测试,但最终的二进制文件应该在树莓派上运行。

我需要调用syscall.Reboot(syscall.LINUX_REBOOT_CMD_POWER_OFF),这个函数在树莓派上可以正常工作,但是在Windows上需要将其注释掉以测试二进制文件,并在构建树莓派上的代码时取消注释。
即使我测试操作系统以确定是否调用了该函数,由于它在Windows上似乎不存在,Go也不会构建它。
是否有办法在Windows上构建代码,即使该函数不存在?

我不希望在树莓派上进行任何代码编辑,而且我不能使用WSL,因为我需要与USB设备等进行通信,这在本机操作系统上构建时更容易实现。

英文:

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

答案1

得分: 1

听起来你想要条件编译,就像这里描述的那样:

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

你可以在你的包中有两个源文件,它们使用_os命名法作为名称。这两个文件都导出一个执行适当行为的函数。

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")
}

当你执行go build时,它不会在Windows上编译reboot_linux.go,也不会在Linux上编译reboot_windows.go

有趣的是,这正是Go在自己的源代码中分离出syscall包的实现方式。

英文:

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.

huangapple
  • 本文由 发表于 2022年4月30日 22:22:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/72069318.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定