用CGO构建git子模块

时间:2018-09-23 12:00:25

标签: go cgo

我需要将git子模块中的C ++代码包括到我的GO程序中,并具有以下代码:

$ tree
├── git-imaginary-submodule
│   ├── test.cc
│   └── test.h
└── main.go

1 directory, 3 files

$ cat main.go
package main

//#cgo CPPFLAGS: -g -I${SRCDIR}/git-imaginary-submodule
//#cgo CFLAGS: -g -I${SRCDIR}/git-imaginary-submodule
//#include "test.h"
import "C"

import (
    "log"
)

func main() {
    log.Println(C.test())
}

运行go build时,我有以下内容:

$ go build
# github.com/shagabutdinov/stackoverflow-go-include-question/nope
/usr/bin/ld: $WORK/b001/_x002.o: in function `_cgo_bc718ee76ee7_Cfunc_test':
/tmp/go-build/cgo-gcc-prolog:43: undefined reference to `test'
collect2: error: ld returned 1 exit status

但是当C ++代码位于本地时,构建就可以了:

$ tree
.
├── main.go
├── test.cc
└── test.h

0 directories, 3 files
$ go build .
# ok

$ cat main.go 
package main

//#include "test.h"
import "C"

import (
  "log"
)

func main() {
  log.Println(C.test())
}

以下是test.htest.cc的源代码:

$ cat test.h 
#ifdef __cplusplus
extern "C" {
#endif
  int test();
#ifdef __cplusplus
}
#endif

$ cat test.cc
#include <vector>
#include "test.h"

int test() {
  std::vector<int> vector = {1, 2};
  return vector[0] + vector[1];
}

如何使用位于另一个目录中的C ++代码?

0 个答案:

没有答案