About
When I'm doing C / C ++, I often wish I could write it in golang. I wrote Hello ()
in C / C ++ from golang to [cgo](https://golang.org/cmd/ Let's call it with cgo /).
version | |
---|---|
Ubuntu | 17.10 |
gcc | 7.2.0 |
golang | 1.8.3 |
c_hello.h
#ifndef C_HELLO_H_
#define C_HELLO_H_
void Hello(const char*);
#endif
c_hello.c
#include <stdio.h>
#include "c_hello.h"
void Hello(const char* name) {
printf("hello %s\n", name);
};
c_hello.go
package main
/*
#cgo LDFLAGS: ./chello.o
#include "chello.h"
*/
import "C"
func main() {
C.Hello(C.CString("Qiita"))
}
Compile & run
% gcc c_hello.c -c
% go run c_hello.go
% hello Qiita
hello.hpp
#ifndef HELLO_H_
#define HELLO_H_
#ifdef __cplusplus
extern "C" {
#endif
void Hello(const char*);
#ifdef __cplusplus
}
#endif
#endif
hello.cpp
#include <cstdio>
#include "hello.hpp"
void Hello(const char* name) {
std::printf("hello %s\n", name);
};
hello.go
package main
/*
#cgo LDFLAGS: ./hello.o
#include "hello.hpp"
*/
import "C"
func main() {
C.Hello(C.CString("Qiita"))
}
Compile & run
% gcc -lstdc++ hello.cpp -c
% go run hello.go
% hello Qiita
# cgo
, but all I had to do was specify the object file in LDFLAGS.Recommended Posts