Calling C-lang 함수 from golang

Look! there's a flower!·2025년 5월 22일

1. golang에서 바로 C함수를 사용 - import "C" comment block 사용

<샘플>

// main.go
package main

/*
#include <stdio.h>
#include <stdlib.h>

// Simple C function
void helloFromC() {
    printf("Hello from C!\n");
}

// C function with arguments
int add(int a, int b) {
    return a + b;
}
*/
import "C"
import "fmt"

func main() {
    // Call C function without args
    C.helloFromC()

    // Call C function with args
    result := C.add(3, 4)
    fmt.Printf("Result from C.add: %d\n", result)
}

2. 별도 C-파일을 사용하는 방법

<샘플>
1) C샘플: helper.c, helper.h

  • File: helper.c
#include <stdio.h>

void helloFromC() {
    printf("Hello from separate C file!\n");
}

int multiply(int a, int b) {
    return a * b;
}
  • helper.h
#ifndef HELPER_H
#define HELPER_H

void helloFromC();
int multiply(int a, int b);

#endif

2) golang 샘플: main.go

  • File: main.go
package main

/*
#cgo CFLAGS: -I.
#cgo LDFLAGS: -L. -lhelper
#include "helper.h"
*/
import "C"
import "fmt"

func main() {
    C.helloFromC()
    result := C.multiply(5, 6)
    fmt.Println("Result from C.multiply:", int(result))
}

3) 컴파일 및 실행 방법

  • 먼저 C를 컴파일 해서 라이브러리로 만듬
    $ gcc -c helper.c -o helper.o
    $ ar rcs libhelper.a helper.o
  • 그런 후 golang은 기존처럼 실행
    $ go run main.go
profile
Why don't you take a look around for a moment?

0개의 댓글