1

I am trying to create a CGO program with separate C source file in the same directory. As mentioned in the official Cgo docs, Cgo will compile all C files in the same directory but in this case, it is not compiling the C file. And later gives a linker error.

myTest.go

package main

/*

#include <stdlib.h>
#include "myTest.h"

*/
import "C"
import "unsafe"

func Print(s string) {
    cs := C.CString(s)
    C.print_str(cs)
    C.free(unsafe.Pointer(cs))
}

func main() {
    str1 := "hi how are you\n"
    Print(str1)
}

myTest.h

void print_str(char *s);

myTest.c

#include "stdio.h"

void print_str(char *s)
{
    printf("%s\n", s?s:"nil");
}

While compiling, I am getting the following error:

> go build myTest.go

# command-line-arguments
/tmp/go-build989557946/b001/_x002.o: In function `_cgo_4c80c9e4eaf0_Cfunc_print_str':
/tmp/go-build/cgo-gcc-prolog:49: undefined reference to `print_str'
collect2: error: ld returned 1 exit status

Go version is:

> go version
go version go1.10 linux/amd64
Kanwar Saad
  • 2,138
  • 2
  • 21
  • 27
  • You're calling `go build` with a single file, so it's only going to build a single file. You should be building "packages", see [How to Write Go Code](https://golang.org/doc/code.html) – JimB Mar 29 '18 at 14:17
  • How did you fix your problem? I'm having the same issue... – reijin Nov 15 '18 at 23:09
  • Answering myself: according to https://golang.org/doc/code.html the important part is to use "main" as the package name if the .go file should be executed (= conatins the "main" function). That was my mistake! – reijin Nov 15 '18 at 23:46

1 Answers1

6
$ go help build
usage: go build [-o output] [-i] [build flags] [packages]

Build compiles the packages named by the import paths,
along with their dependencies, but it does not install the results.

If the arguments to build are a list of .go files, build treats
them as a list of source files specifying a single package.

<< SNIP>>

If the arguments to build are a list of .go files, build treats them as a list of source files specifying a single package.

> go build myTest.go

builds file myTest.go

Run

> go build
peterSO
  • 158,998
  • 31
  • 281
  • 276
  • In my case the package is called "main". I had to create a folder called "main" and put all of the files there so I could "go build -o myExecutable main". Thanks for the answer. – Th3B0Y Jul 27 '18 at 15:25
  • Correction the previous comment. The command is "go build -o myExecutable ./main" – Th3B0Y Jul 27 '18 at 15:31