Integrating Go Code into Existing C Projects
Prior to Go 1.5, integrating Go code into C projects was challenging. However, with the introduction of the -buildmode=c-archive flag, it has become possible to call Go code from within C programs.
To generate the necessary header files and archive for linking with C code, follow these steps:
go build -buildmode=c-archive <Go_source_file>.go
This will generate an archive (e.g., foo.a) and a header file (e.g., foo.h).
In your C code, include the generated header file and use the exported functions following the CGo naming conventions. For example:
#include "foo.h" int main(int argc, char **argv) { PrintInt(42); return 0; }
To compile the C program, use a command like:
gcc -pthread foo.c foo.a -o foo
Additional Notes:
The above is the detailed content of How Can I Integrate Go Code into Existing C Projects?. For more information, please follow other related articles on the PHP Chinese website!