builder, cgo: support function definitions in CGo headers

For example, the following did not work before but does work with this
change:

    // int add(int a, int b) {
    //   return a + b;
    // }
    import "C"

    func main() {
        println("add:", C.add(3, 5))
    }

Even better, the functions in the header are compiled together with the
rest of the Go code and so they can be optimized together! Currently,
inlining is not yet allowed but const-propagation across functions
works. This should be improved in the future.
This commit is contained in:
Ayke van Laethem
2021-09-17 02:41:45 +02:00
committed by Ron Evans
parent 138add2b96
commit e02727679f
7 changed files with 86 additions and 10 deletions
+3 -1
View File
@@ -72,6 +72,7 @@ type Package struct {
Files []*ast.File
FileHashes map[string][]byte
CFlags []string // CFlags used during CGo preprocessing (only set if CGo is used)
CGoHeaders []string // text above 'import "C"' lines
Pkg *types.Package
info types.Info
}
@@ -397,8 +398,9 @@ func (p *Package) parseFiles() ([]*ast.File, error) {
if p.program.clangHeaders != "" {
initialCFlags = append(initialCFlags, "-Xclang", "-internal-isystem", "-Xclang", p.program.clangHeaders)
}
generated, cflags, ldflags, accessedFiles, errs := cgo.Process(files, p.program.workingDir, p.program.fset, initialCFlags)
generated, headerCode, cflags, ldflags, accessedFiles, errs := cgo.Process(files, p.program.workingDir, p.program.fset, initialCFlags)
p.CFlags = append(initialCFlags, cflags...)
p.CGoHeaders = headerCode
for path, hash := range accessedFiles {
p.FileHashes[path] = hash
}