cgo: os/arch dependent #cgo directives

This enables #cgo directives to contain a os/arch
specification which restricts the definition of
the given option to matching systems.

For example:

#cgo amd64 CFLAGS: -DAMD64=1
#cgo linux CFLAGS: -DLINUX=1
#cgo linux/amd64 CFLAGS: -DLINUX_ON_AMD64=1

R=rsc
CC=golang-dev
https://golang.org/cl/4121048
This commit is contained in:
Gustavo Niemeyer 2011-02-03 13:51:47 -05:00 committed by Russ Cox
parent 3f61184e1b
commit ab15a978fb
2 changed files with 27 additions and 3 deletions

View file

@ -25,9 +25,12 @@ the package. For example:
CFLAGS and LDFLAGS may be defined with pseudo #cgo directives CFLAGS and LDFLAGS may be defined with pseudo #cgo directives
within these comments to tweak the behavior of gcc. Values defined within these comments to tweak the behavior of gcc. Values defined
in multiple directives are concatenated together. For example: in multiple directives are concatenated together. Options prefixed
by $GOOS, $GOARCH, or $GOOS/$GOARCH are only defined in matching
systems. For example:
// #cgo CFLAGS: -DPNG_DEBUG=1 // #cgo CFLAGS: -DPNG_DEBUG=1
// #cgo linux CFLAGS: -DLINUX=1
// #cgo LDFLAGS: -lpng // #cgo LDFLAGS: -lpng
// #include <png.h> // #include <png.h>
import "C" import "C"

View file

@ -19,6 +19,7 @@ import (
"go/parser" "go/parser"
"go/token" "go/token"
"os" "os"
"runtime"
"strconv" "strconv"
"strings" "strings"
"unicode" "unicode"
@ -66,6 +67,8 @@ func cname(s string) string {
func (p *Package) ParseFlags(f *File, srcfile string) { func (p *Package) ParseFlags(f *File, srcfile string) {
linesIn := strings.Split(f.Preamble, "\n", -1) linesIn := strings.Split(f.Preamble, "\n", -1)
linesOut := make([]string, 0, len(linesIn)) linesOut := make([]string, 0, len(linesIn))
NextLine:
for _, line := range linesIn { for _, line := range linesIn {
l := strings.TrimSpace(line) l := strings.TrimSpace(line)
if len(l) < 5 || l[:4] != "#cgo" || !unicode.IsSpace(int(l[4])) { if len(l) < 5 || l[:4] != "#cgo" || !unicode.IsSpace(int(l[4])) {
@ -79,11 +82,29 @@ func (p *Package) ParseFlags(f *File, srcfile string) {
fatal("%s: bad #cgo line: %s", srcfile, line) fatal("%s: bad #cgo line: %s", srcfile, line)
} }
k := fields[0] var k string
v := strings.TrimSpace(fields[1]) kf := strings.Fields(fields[0])
switch len(kf) {
case 1:
k = kf[0]
case 2:
k = kf[1]
switch kf[0] {
case runtime.GOOS:
case runtime.GOARCH:
case runtime.GOOS + "/" + runtime.GOARCH:
default:
continue NextLine
}
default:
fatal("%s: bad #cgo option: %s", srcfile, fields[0])
}
if k != "CFLAGS" && k != "LDFLAGS" { if k != "CFLAGS" && k != "LDFLAGS" {
fatal("%s: unsupported #cgo option %s", srcfile, k) fatal("%s: unsupported #cgo option %s", srcfile, k)
} }
v := strings.TrimSpace(fields[1])
args, err := splitQuoted(v) args, err := splitQuoted(v)
if err != nil { if err != nil {
fatal("%s: bad #cgo option %s: %s", srcfile, k, err.String()) fatal("%s: bad #cgo option %s: %s", srcfile, k, err.String())