const if语句在Go中是否与#ifdef宏执行相同的操作?

huangapple go评论73阅读模式
英文:

Do const if statements do the same thing as #ifdef macros in Go?

问题

在Go语言中没有文本预处理。与Java和其他类似的语言一样,如果我想删除一段代码,我可以使用一个const值,并用一个if语句将代码包围起来。

如果我这样做,编译器会从AST(抽象语法树)中优化代码并生成优化后的代码吗?还是条件每次都会被执行?

编辑:如果我想复制#ifdef的功能,最好的方法是什么?

英文:

There's no text preprocessing in Go. Like Java and others like it, if I want to remove a block of code I can use a const value and surround the code with an if.

If I do this, does the compiler optimise the code from the AST and out of the generated code? Or is the condition executed each time?

EDIT: If I want to replicate #ifdef what's the best way to do it?

答案1

得分: 9

如果语句中的条件是常量,那么与#ifdef不同,因为无论如何都会编译其中的代码。然而,编译器会在可能的情况下进行优化。考虑以下程序:

package main

import (
	"fmt"
)

func main() {
	if false {
		fmt.Println("Hello, world!")
	}
}

如果我们运行go tool 6g -S test.go,这是main函数的汇编输出:

--- prog list "main" ---
0000 (test.go:7) TEXT    main+0(SB),$40-0
0001 (test.go:11) RET     ,

无用的代码已经消失,所以它只是返回。

如果您确实需要有条件地编译代码的一部分,最好通过构建系统来实现。

英文:

If statements with constant conditions are not the same as #ifdef because the code inside is always compiled no matter what. However, the compilers do optimize it away when possible. Consider this program:

package main

import (
	"fmt"
)

func main() {
	if false {
		fmt.Println("Hello, world!")
	}
}

If we run go tool 6g -S test.go, here's the assembly output for the main function:

--- prog list "main" ---
0000 (test.go:7) TEXT    main+0(SB),$40-0
0001 (test.go:11) RET     ,

The dead code is gone so all it does is return.

If you do need to actually conditionally compile parts of your code, it's best to do it through the build system.

huangapple
  • 本文由 发表于 2012年6月29日 05:02:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/11252846.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定