Building executable for code with cgo produces link errors

64 views
Skip to first unread message

Nicholas Yue

unread,
Jan 22, 2021, 1:21:55 AM1/22/21
to golang-nuts
Hi,

  I am using Go 1.15 on Ubuntu 18.04

  I am learning about cgo via the following tutorial


  I have the following two files which I am able to run via

  go run cgo_main.go

  Knowing that it runs, I'd like to build it into an executable but I get the following errors

```
$ go build .
/tmp/go-build161353644/b001/_x003.o: In function `printf':
/usr/include/x86_64-linux-gnu/bits/stdio2.h:104: multiple definition of `Hello'
/tmp/go-build161353644/b001/_x002.o:/usr/include/x86_64-linux-gnu/bits/stdio2.h:104: first defined here
collect2: error: ld returned 1 exit status
```
```
// cgo_main.go
package main

/*
#include "hello.c"
*/
import "C"
import (
"errors"
"log"
)

func main() {
//Call to void function without params
err := Hello()
if err != nil {
log.Fatal(err)
}
}

//Hello is a C binding to the Hello World "C" program. As a Go user you could
//use now the Hello function transparently without knowing that it is calling
//a C function
func Hello() error {
_, err := C.Hello() //We ignore first result as it is a void function
if err != nil {
return errors.New("error calling Hello function: " + err.Error())
}

return nil
}

```
```
//hello.c
#include <stdio.h>

void Hello(){
printf("Hello world [cgo]\n");
}

```


Cheers

Ian Lance Taylor

unread,
Jan 22, 2021, 1:39:09 AM1/22/21
to Nicholas Yue, golang-nuts
On Thu, Jan 21, 2021 at 10:21 PM Nicholas Yue <yue.ni...@gmail.com> wrote:
>
> /*
> #include "hello.c"
> */
> import "C"

Doing a #include of "hello.c" is unusual. That is most likely your
problem. The comment before the import "C" is handled as C code. C
code rarely does a #include of a .c file. Normally one does a
#include of a .h file.

Ian
Reply all
Reply to author
Forward
0 new messages