What version of Go are you using (go version)?
$ go version
go version go1.20.2 linux/amd64
Project structure:
Directory structure --
example --> main.go
-->lib
lib.c
lib.h
main.go
package main
// #include "lib/lib.h"
// #include <stdio.h>
// #include <stdlib.h>
import "C"
import (
"fmt"
"unsafe"
)
func main() {
cstrin := C.CString("welcome")
s1 := C.struct_s1{b: cstrin, a: 100}
C.f32_123(&s1)
cs := C.GoString(s1.b)
fmt.Println(cs)
fmt.Println(s1)
C.free(unsafe.Pointer(cstrin))
}
lib/lib.c
#include <stdlib.h>
#include <stdio.h>
void printc(char *str, int *t)
{
str = "Test";
printf("%d\n", *t);
*t = 30;
printf("%s\n", str);
}
void f32_123(struct s1 *s)
{
printf("%s\n", s->b);
s->a = 10;
s->b = "Hello123";
printf("%d\n", s->a);
printf("%s\n", s->b);
}
lib/lib.h
struct s1 {
int a;
char *b;
};
void printc(char *str, int *t);
void f32_123(struct s1 *s);
Error while compiling
/usr/local/go/pkg/tool/linux_amd64/link: running gcc failed: exit status 1
/usr/bin/ld: /tmp/go-link-3024881602/000001.o: in function _cgo_cf24297edd23_Cfunc_f32_123': /tmp/go-build/cgo-gcc-prolog:49: undefined reference to f32_123'
collect2: error: ld returned 1 exit status
I am expecting the code to compile successfully, but somehow it is not. If I've read the documentation correctly, then I have to keep lib.c
and lib.h
in the same directory with the main.go
file. But I am not sure if this can be achieved or I am doing something wrong.
If I keep all the files into same directory example then compile is successful.
If I keep
lib.c
andlib.h
into subdir then compile failsIf I remove one function
f32_123
from main.go then also compile is successful and that is pretty strange and that is the reason opening this bug to get more understanding why compile has not issue with printc function whenlib.h
andlib.c
is in subdir.