Using Go on existing C project

前端 未结 2 1521
天命终不由人
天命终不由人 2021-01-13 02:39

I have a program entirely written in C that uses multiple object (.o) files in it. These files are all packed inside an archive file (.a) which, in

相关标签:
2条回答
  • 2021-01-13 03:14

    This may not be what you want, but in Go 1.5, that's coming this August, you'll be able to build C-compatible libraries with the go tool. So with this in your _main.c

    #include <stdio.h>
    
    int main()
    {
        char *string_to_pass = NULL;
        if (asprintf(&string_to_pass, "This is a test.") < 0) {
            printf("asprintf fail");
            return -1;
        }
    
        PrintString(string_to_pass);
        return 0;
    }
    

    and this in your main.go

    package main
    
    import "C"
    import "fmt"
    
    //export PrintString
    func PrintString(cs *C.char) {
        s := C.GoString(cs)
        fmt.Println(s)
    }
    
    func main() {}
    

    You can do, for static library:

    go build -buildmode c-archive -o mygopkg.a
    gcc -o main _main.c mygopkg.a -lpthread
    

    For shared library:

    go build -buildmode c-shared -o mygopkg.so
    LD_RUN_PATH=$(pwd) gcc -o main _main.c mygopkg.so -lpthread
    

    (LD_RUN_PATH is here to make the linker look for the shared library in the same directory you're building.)

    See the Go execution modes design document for more info.

    0 讨论(0)
  • 2021-01-13 03:26

    There currently isn't a supported way to do what you want. Go always needs the support of its runtime, and the entry point for that is always main. AFAIK, gccgo also makes these same assumptions, and doesn't provide a way to easily link into from other programs.

    If you want to do this in a supported manner, you will have to wait until go1.5+ where work is being done to compile shared libraries from Go code.

    If you really want to hack on this now, you can look into how the Android port works using the default gc toolchain with -linkmode external, which renames main in the object file and calls it externally.

    0 讨论(0)
提交回复
热议问题