0

C language uses multiple go static libraries, reporting duplicat symbols error

file hello.go

// file hello.go 

package main

import "C"
    
func main() {}

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

file world.go

// file world.go 

package main

import "C"

func main() {}

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

build command

platform: darwin

build command:

go build -buildmode c-archive -o libhello.a hello.go

go build -buildmode c-archive -o libworld.a world.go

files:

libhello.h libhello.a libworld.h libworld.a hello.go world.go

file main.c

// file main.c
#include "libhello.h"
#include "libworld.h"

int main()
{
    hello();
    world();
}

build command:
gcc -o cc -L. -lhello -lworld main.c

The error is

duplicate symbol '__cgo_panic' in: ./libhello.a(go.o) ./libworld.a(go.o) duplicate symbol '__cgo_topofstack' in: ./libhello.a(go.o) ./libworld.a(go.o) duplicate symbol '_crosscall2' in: ./libhello.a(go.o) ./libworld.a(go.o) ld: 3 duplicate symbols for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

screenshot of the error

Using a dynamic library will not report this error, but I need to use a static library

kostix
  • 51,517
  • 14
  • 93
  • 176
  • duplicate symbol '__cgo_panic' in: ./libhello.a(go.o) ./libworld.a(go.o) duplicate symbol '__cgo_topofstack' in: ./libhello.a(go.o) ./libworld.a(go.o) duplicate symbol '_crosscall2' in: ./libhello.a(go.o) ./libworld.a(go.o) ld: 3 duplicate symbols for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) – JieLin Dee Sep 28 '21 at 13:30
  • 3
    Don't add details in comments, edit your post – Jorengarenar Sep 28 '21 at 13:33
  • 3
    Please, next time [do something like this](https://www.google.com/search?q=%22duplicate+symbol+%27__cgo_panic%27%22) before posting. In particular, [this question was already asked](https://stackoverflow.com/q/56537928/720999). – kostix Sep 28 '21 at 13:46
  • _Caveat:_ I don't know `go`. A _guess_: You do: `func main() {}` in _both_ your `.go` files. Try commenting it out in one or _both_ of them. I suspect that when the compiler sees a `main` _definition_ it statically links in requisite helper/wrapper functions such as `__cgo_panic` et. al. Thus, instead of just one `.o` having the definitions, you have two. Since `hello.go` and `world.go` are intended to create [separate] _libraries_, I don't know why you would want a `main` function in _either_ of them. If you want/need a go `main` function, it would/should go into (e.g.) `main.go` – Craig Estey Sep 28 '21 at 18:10

0 Answers0