Call cxx-static-lib in Go
How to compile and call a CXX-static library in Golang
touch some files first
1 | # create a directory for this project |
Create a header file: hi.h
In comparison with c-static-lib, the header file here has some extra contents
extern "C" { ... }
mainly to be compatible with C++ compilers.
1 |
|
Create a source file: hi.cpp
Different from c-static-lib, the c++ source file must include the header file.
#include "hi.h"
1 |
|
Create a main file: main.go
Compared to c-static-lib, the LDFLAGS here has an extra -l stdc++
to link the C++
standard library.
1 | package main |
Compile the source file into a static library
1 | g++ -c ./lib/hi.cpp -o ./lib/hi.o |
Run
1 | # go run directly |
Summary
The key points are different from call c-static-lib:
- use
extern "C" { ... }
in header file to be compatible with C++ compilers - source file must include the header file
- add
-l stdc++
toLDFLAGS
- use
g++
to compile the source file into a static library
If you are not sure the static lib is c
or c++
,
your golang code can always use the c++
way to call it, which is more compatible.
Always add
-l stdc++
toLDFLAGS