The short answer: Kind of?
It sounds like what you're trying to accomplish is a shared library.
The Go compiler has been able to produce shared libraries since 1.5 with the -buildmode=c-shared
build flag:
go build -o helloworld.so -buildmode=c-shared
And, as of Go 1.10, the functionality is additionally supported on Windows
So, compiling to DLL is also a one-liner:
go build -o helloworld.dll -buildmode=c-shared
The problem that you're going to run into is actually using those libraries, especially in a cross operating system way:
In *nix, you can use CGO to accomplish this:
package example
// #cgo LDFLAGS: -lfoo
//
// #include <foo.h>
import "C"
func main() {
C.bar()
}
Windows gets its own Wiki (who's surprised?).
I'll leave you with a few thoughts on this:
- There's nothing wrong with a 15-20mb binary (although, you should try upx to shave off some of that fat because why not?), you should be concerned when you're pushing 10s of 100s of gigs. Space is cheap these days.
- Writing something that can be compiled into a single binary, regardless of OS, is one of the best perks of Go.
-
CGO_ENABLED=0
saves you a ton of space from your binaries. Keeping it enabled (which you need to use these features), isn't doing you any favors.
- You're right to assume that since the compiler can't optimize for included libraries, that ultimately you're not going to save much, if any space, in small use cases.
My last point, then I'll stop preaching at you: Focus on writing code. Binary size should not be your concern unless you're trying to fit on embedded devices.
Good luck friend.