1

I know how to make a function that adds up all the parameters given to it and one for subtraction and I wanted to make a simple math library for adding and subtracting and multiplying and dividing, but my internet searches for how to compile into a library came up with no results. I would like to know if there is a way to make a .go into a library and if so how do you do it. I am still very new to Go. If you know how to please tell me

kostix
  • 51,517
  • 14
  • 93
  • 176
  • 1
    Read [this](https://golang.org/doc/code.html), [this](http://dave.cheney.net/2014/12/01/five-suggestions-for-setting-up-a-go-project) and [this](https://github.com/golang/go/wiki/GithubCodeLayout) for a start. Oh, and [this](https://blog.golang.org/organizing-go-code), too. – kostix May 19 '16 at 14:12

1 Answers1

1

If you run go install on your package, it will create a static library with the name of that package for you, and place it in your GOPATH/pkg/ARCH/packageName/packageName.a. For example, if you have your $GOPATH set as /home/yourname/go, you can create the following file:

/home/yourname/go/src/myMath/myMath.go

with the content of:

package myMath

func MyAdd(/* .... */) { // Capatalize the name of the function to allow it to be accessible from outside of this package
   // Do stuff
}

Now, if you do a go install, you will have a myMath.a library in the directory above.

To use this library from another go package, myStats say, you can do the following:

package myStats

import "myMath" // import your library. notice the "" around the name

func someFunction(/* .... */) {
   r := myMath.MyAdd(/* ..... */)
}

Notice again that you have to capitalized the name of the functions you wish to be used from outside of your package. For example, if your add function was called myAdd, then it would not been accessible from myStats even if you do import the myMath package.

Edit fixed some errors based on the comments from @icza, below.

physphun
  • 376
  • 3
  • 6
  • 1
    Package folder is `pkg` (not `pack`), and `go build` does not create a `*.a` file (it discards the result). See [What does go build build?](http://stackoverflow.com/questions/30612611/what-does-go-build-build) – icza May 19 '16 at 16:24