go build with cgo displays undefined reference

31 views Asked by At

This is my directory structure before any build process:

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

Then, I compiled C files and created object (.o) files like this:

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

Next, I created archive (.a) file:

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

This is main.go:

package main

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

func main() {
    C.execute()
}

This is 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

Now, when I try to build main.go, I get this error:

$ 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

What am I doing wrong here?

1

There are 1 answers

0
ayivaak On

I found the problem, I did not include proper LDFLAGS. This is the correct 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()
}