<샘플>
// 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)
}
<샘플>
1) C샘플: helper.c, helper.h
#include <stdio.h>
void helloFromC() {
printf("Hello from separate C file!\n");
}
int multiply(int a, int b) {
return a * b;
}
#ifndef HELPER_H
#define HELPER_H
void helloFromC();
int multiply(int a, int b);
#endif
2) golang 샘플: 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) 컴파일 및 실행 방법