How to compile and call a CXX-static library in Golang
touch some files first
|
|
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.
|
|
Create a source file: hi.cpp
Different from c-static-lib, the c++ source file must include the header file.
#include “hi.h”
|
|
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.
|
|
Compile the source file into a static library
|
|
Run
|
|
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