使用 cgo 构建显示未定义的引用

问题描述 投票:0回答:1

这是我在任何构建过程之前的目录结构:

$ tree .
.
├── go.mod
├── include
│   └── calc.h
├── lib
├── main.go
└── src
    ├── calc.c
    └── execute.c

然后,我编译了 C 文件并创建了对象 (.o) 文件,如下所示:

$ gcc src/* -Iinclude -c 
$ ls
calc.o  execute.o  go.mod  include  lib  main.go  src

接下来,我创建了存档(.a)文件:

$ ar -rcs lib/libcalc.a execute.o calc.o
$ ls lib
libcalc.a

这是main.go:

package main

/*
#cgo LDFLAGS: -L${SRCDIR}/lib
#cgo CFLAGS: -I${SRCDIR}/include
#include "include/calc.h"
*/
import "C"

func main() {
    C.execute()
}

这是 calc.h:

// calc.h
#ifndef CALC_H
#define CALC_H

typedef enum operation_t {
    ADDITION = 0,
    SUBTRACTION,
    MULTIPLICATION,
    DIVISION
} operation;

typedef enum error_t {
    OP_OK = 0,
    OP_UNSUPPORTED
} error;

typedef struct calc_info_t {
    int num1;
    int num2;
    operation  op;
    double result;
} calc_info;

error calculate(calc_info *cc);
int execute();

#endif

现在,当我尝试构建 main.go 时,我收到此错误:

$ go build main.go
# command-line-arguments
/usr/bin/ld: $WORK/b001/_x002.o: in function `_cgo_83eef7989c3e_Cfunc_execute':
/tmp/go-build/cgo-gcc-prolog:52: undefined reference to `execute'
collect2: error: ld returned 1 exit status

我在这里做错了什么?

c go cgo
1个回答
0
投票

我发现了问题,我没有包含正确的LDFLAGS。这是正确的 main.go:

package main

/*
#cgo LDFLAGS: -L${SRCDIR}/lib -l calc
#cgo CFLAGS: -I${SRCDIR}/include
#include "include/calc.h"
*/
import "C"

func main() {
    C.execute()
}

© www.soinside.com 2019 - 2024. All rights reserved.