LoginSignup
13
7

More than 5 years have passed since last update.

Goでマクロを使うなんちゃって実装

Last updated at Posted at 2015-06-05

Goでプリプロセッサ的なことをマクロをつかってできないのかなあ、みたいな試み。

その1

package main

/*
#define myint_def 12345
*/
import "C" 
import "fmt"

func main() {
  fmt.Println(C.myint_def)
}

GitHubのGolangリポジトリから発掘した
それなんか違くない? って言われたら反論できません。

その2

hoge.go.p
package main

import "fmt"

#define myval 12345

func main(){
  fmt.Println(myval)
#ifdef DEBUG
  fmt.Println("this is debuguuuuuuuuuu!!")
#endif
}
実行
$ cpp -P -o a.go hoge.go.p | go run a.go
12345
$ cpp -D DEBUG -P -o b.go hoge.go.p | go run b.go
12345
this is debuguuuuuuuuuu!!

go macroとかでググったら見つけた方法
お、おう。って感じ。
go fmtできなくなるのも残念。

普通にconst使いましょう

こんな感じでそろえて

env/debug.go
// +build debug

package env
const DEBUG = true
env/no_debug.go
// +build !debug

package env
const DEBUG = false
hoge.go
package main

import (
  "fmt"
  "./env"
)

const myval = 123456789

func main() {
  fmt.Println(myval)

  if env.DEBUG {
     fmt.Println("debugggggggggg")
  }
}
$ go build -o a.out 
$ go build -tags=debug -o b.out
$ ls -l
-rwxr-xr-x 1 umanoda umanoda 1944936  6月  6 00:26 a.out
-rwxr-xr-x 1 umanoda umanoda 1944944  6月  6 00:26 b.out
$ ./a.out
123456789
$ ./b.out
123456789
debugggggggggg

デバッグメッセージを表示するほうは、if内の処理が残るため、ファイルサイズが大きくなっているようです。
なお// +build tag のあとは一行開けないとビルドエラーが出ます。Goは改行を入れたり入れなかったりで、エラーになったりならなかったりがあるから、たまにハマる。

13
7
4

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
13
7