简体   繁体   中英

Is there a way to include multiple c-archive packages in a single binary

I'm trying to include multiple Go c-archive packages in a single C binary, but I'm getting multiple definition errors due to the full runtime being included in each c-archive.

I've tried putting multiple packages in the same c-archive but go build does not allow this.

I've also tried removing go.o from all the archives except one, but it seems my own Go code is also in that object file so that doesn't work, and it's even the reason I get multiple defines instead of the linker ignoring go.o from subsequent archives.

It would probably work to use c-shared instead of c-archive , but I don't wish to do that as I then have to put the shared libraries on my target machine, which is more complicated compared to just putting the final program binary there. I'd like everything to be statically linked if possible.

Is there a way to get this working? I can accept a linux only solution if that matters (some GNU ld trickery probably in that case).

Putting everything in a single Go package is not really an option, since it's a fairly large code base and there would be different programs wanting different parts. It would have to be an auto-generated package in that case.

Full steps to reproduce the problem:

cd $GOPATH/src
mkdir a b
cat > a/a.go <<EOT
package main

import "C"

//export a
func a() {
    println("a")
}

func main() {}
EOT
cat > b/b.go <<EOT
package main

import "C"

//export b
func b() {
    println("b")
}

func main() {}
EOT
cat > test.c <<EOT
#include "a.h"
#include "b.h"

int
main(int argc, char *argv[]) {
    a();
    b();
}
EOT
go build -buildmode=c-archive -o a.a a
go build -buildmode=c-archive -o b.a b
gcc test.c a.a b.a

I fumbled my way through this today after coming across your question.

The key is to define a single main package that imports the packages that you need and build them all together with a single "go install" command. I was unable to get this to work with "go build".

package main //import golib

import (
        _ "golib/operations/bar"
        _ "golib/foo"
)
func main() {}

go install  -buildmode=c-archive golib

This will place your .a and .h files under a pkg/arch/golib directory. You can include the .h files as usual, but you only need to link against golib.a

aaron@aaron-laptop:~/code/pkg/linux_amd64$ ls
github.com  golang.org  golib  golib.a
aaron@aaron-laptop:~/code/pkg/linux_amd64$ ls golib
foo.a  foo.h operations  
aaron@aaron-laptop:~/code/pkg/linux_amd64$ ls golib/operations
bar.a bar.h

Note that go will complain about unused packages if you omit the underscore in the import.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM