LoginSignup
9
9

More than 5 years have passed since last update.

cgoやってみた

Posted at

About

C/C++をやっているとgolangで書けたらいいのにと思うことがよくあります. C/C++で書いたHello()をgolangからcgoで呼び出してみます.

試してみた環境

version
Ubuntu 17.10
gcc 7.2.0
golang 1.8.3

C言語でHello World

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"))
}

コンパイル&実行
bash
% gcc c_hello.c -c
% go run c_hello.go
% hello Qiita

C++でHello World

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"))
}

コンパイル&実行
bash
% gcc -lstdc++ hello.cpp -c
% go run hello.go
% hello Qiita

所感

  • #cgoで結構エラーで詰まったが, LDFLAGSにオブジェクトファイルを指定するだけでよかった.
  • `import "C"の上のコメントアウトしているCコードとの間に空行があるとエラーになる.
9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9