LoginSignup
7
7

More than 5 years have passed since last update.

Makefile から、Go の変数を代入する

Posted at

Go のプロジェクトで、Makefile を使っている例があるが、今日ちょっとした Tips を学んだので、メモしておきたい。

package main

import "fmt"

var GIT_BASE_DIR = ""

func main() {
    fmt.Printf("GitCurrentBaseDir: %s¥n", GIT_BASE_DIR)
}

プロジェクトにこんな感じの go のコードがあった。明らかに GIT_BASE_DIR には何も入っていない。実行すると

$ go run cmd/*.go
GitCurrentBaseDir: ¥n

これは何だろう?と思ったら、Makefile から、 Go の変数に代入するテクニックがあるようだ。

先の main.go を、cmd ディレクトリ配下において、次のような Makefile を書いてみた。


GIT_BASE_DIR := $(shell git rev-parse --show-toplevel)

run:
    go run  -ldflags="-X main.GIT_BASE_DIR=${GIT_BASE_DIR}" **/*.go

実行すると、正しく、git のルートディレクトリが取得できていて、それが代入されているのがわかる。

$ make run
go run  -ldflags="-X main.GIT_BASE_DIR=/Users/ushio/Codes/gosample/src/github.com/TsuyoshiUshio/GoWithMake" **/*.go
GitCurrentBaseDir: /Users/ushio/Codes/gosample/src/github.com/TsuyoshiUshio/GoWithMake¥n

これは、Go Tool Link の機能らしい

-X importpath.name=value
    Set the value of the string variable in importpath named name to value.
    Note that before Go 1.5 this option took two separate arguments.
    Now it takes one argument split on the first = sign.

Go で、ディレクトリの絶対パスとか取りたい時に有効かもですね。

参考

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7