0

I need to include a C++ code from git submodule to my GO program and have following code:

$ 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())
}

When I run go build I have following:

$ 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

But when the C++ code is locally located build is fine:

$ 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())
}

Here are source code for test.h and test.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];
}

How can I use C++ code located in another directory?

Leonid Shagabutdinov
  • 1,100
  • 10
  • 14
  • 1
    Possible duplicate of [How to add C files in a subdirectory as part of go build by using pseudo CGO directives?](https://stackoverflow.com/questions/28881072/how-to-add-c-files-in-a-subdirectory-as-part-of-go-build-by-using-pseudo-cgo-dir) – Jack Wilsdon Sep 23 '18 at 17:48
  • Correct, thank you! It is the reply to my question. – Leonid Shagabutdinov Sep 24 '18 at 11:06

0 Answers0