在Go中进行任何导入之前,是否可以设置环境变量?

I'm currently testing the Go-SDL2 lib, just for fun. I gave the binary to one of my friend but he doesn't have the SDL installed on his machine. So all I want to do (is dance) is to distribute the 4 .so libs with the binary so that it will work fine on other Linux machines. It's pretty easy actually, I just have to set the LD_LIBRARY_PATH to point to the current folder. This is for testing purpose.

The problem is, I have to set this environment variable before I can import the go-sdl2 lib. For now I have a single source file (main.go obviously).

How can I achieve this ? (Is it even possible ?)

One option is to have a script which sets the LD_LIBRARY_PATH environment variable before calling go-sdl2 (in the same script).

The other more interesting option is to use a Docker image, make a Dockerfile based on that image, and install SDL and go in it (like in didstopia/sdl2 ad its Dockerfile, combined with a Golang Dockerfile).

You then have a reproducible standard environment, where you don't need to change LD_LIBRARY_PATH. And you can export that image in order for your friend to experiment with it.

You could, in main, check to see if LD_LIBRARY_PATH is set, and if not, relaunch (using: os.exec)yourself adding the environment variable.

you basically want to use os.Args as your arguments to exec, but also take your environment and add in LD_LIBRARY_PATH

Bash script is definitely a less funky way to do it. But if you really want the go app to do this, you can.

You want something like: (untested)

cmd := os.Command(os.Args[0],os.Args[1:]...)
cmd.Env = append(os.Environ, "LD_LIBRARY_PATH=./wherever")
cmd.StdErr = os.StdErr // repeat for StdIn/StdOut
err := cmd.Run() //blocks until sub process is complete
if err != nil {
   os.Exit(1)
}

Something like that