简体   繁体   中英

How do I call a Go function from C code embedded in cgo

This is super basic, apologies for the rudimentary ask. I've got Go code, which calls a C function (embedded in the same Go package via cgo), which should call back another Go function. Calling the C code works, and the code compiles, but upon linking, the C linker doesn't find the Go function.

cpoc % go build .
# cpoc
Undefined symbols for architecture x86_64:
  "_goLogger", referenced from:
      _cLogger in _x003.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
poc % 

cpoc.go

package main

// #cgo pkg-config: vips
// #include "cpoc.h"
import "C"
import (
    "fmt"
)

// export goLogger
func goLogger() {
    fmt.Println("goLogger")
}

func main() {
    C.cLogger()
}

cpoc.h

#include <stdlib.h>
#include <stdio.h>
#include <glib.h>

extern void goLogger(void);

void cLogger(void);

cpoc.c

#include "cpoc.h"

void cLogger(void)
{
    printf("cLogger\n");
    goLogger();
}

The space between // and export caused the function not be exported.

Answer based on @kostix comment and it was correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM