Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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は改行を入れたり入れなかったりで、エラーになったりならなかったりがあるから、たまにハマる。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away