summaryrefslogtreecommitdiffstats
path: root/misc/cgo/fortran/fortran_test.go
blob: 4604a4dce3e02799764378b3474d22c798d00091 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package fortran

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
	"testing"
)

func TestFortran(t *testing.T) {
	// Find the FORTRAN compiler.
	fc := os.Getenv("FC")
	if fc == "" {
		fc, _ = exec.LookPath("gfortran")
	}
	if fc == "" {
		t.Skip("fortran compiler not found (try setting $FC)")
	}

	var fcExtra []string
	if strings.Contains(fc, "gfortran") {
		// TODO: This duplicates but also diverges from logic from cmd/go
		// itself. For example, cmd/go merely adds -lgfortran without the extra
		// library path work. If this is what's necessary to run gfortran, we
		// should reconcile the logic here and in cmd/go.. Maybe this should
		// become a cmd/go script test to share that logic.

		// Add -m32 if we're targeting 386, in case this is a cross-compile.
		if runtime.GOARCH == "386" {
			fcExtra = append(fcExtra, "-m32")
		}

		// Find libgfortran. If the FORTRAN compiler isn't bundled
		// with the C linker, this may be in a path the C linker can't
		// find on its own. (See #14544)
		libExt := "so"
		switch runtime.GOOS {
		case "darwin":
			libExt = "dylib"
		case "aix":
			libExt = "a"
		}
		libPath, err := exec.Command(fc, append([]string{"-print-file-name=libgfortran." + libExt}, fcExtra...)...).CombinedOutput()
		if err != nil {
			t.Errorf("error invoking %s: %s", fc, err)
		}
		libDir := filepath.Dir(string(libPath))
		cgoLDFlags := os.Getenv("CGO_LDFLAGS")
		cgoLDFlags += " -L " + libDir
		if runtime.GOOS != "aix" {
			cgoLDFlags += " -Wl,-rpath," + libDir
		}
		t.Logf("CGO_LDFLAGS=%s", cgoLDFlags)
		os.Setenv("CGO_LDFLAGS", cgoLDFlags)

	}

	// Do a test build that doesn't involve Go FORTRAN support.
	fcArgs := append([]string{"helloworld/helloworld.f90", "-o", "/dev/null"}, fcExtra...)
	t.Logf("%s %s", fc, fcArgs)
	if err := exec.Command(fc, fcArgs...).Run(); err != nil {
		t.Skipf("skipping Fortran test: could not build helloworld.f90 with %s: %s", fc, err)
	}

	// Finally, run the actual test.
	t.Log("go", "run", "./testdata/testprog")
	out, err := exec.Command("go", "run", "./testdata/testprog").CombinedOutput()
	if err == nil && string(out) != "ok\n" {
		err = fmt.Errorf("expected ok")
	}
	if err != nil {
		t.Errorf("%s\nOutput:\n%s", err, string(out))
	}
}