我正在尝试从 Go 代码中调用 CUDA 函数。
我有以下三个文件。
test.h:
int test_add(void);
test.cu:
__global__ void add(int *a, int *b, int *c){
*c = *a + *b;
}
int test_add(void) {
int a, b, c; // host copies of a, b, c
int *d_a, *d_b, *d_c; // device copies of a, b, c
int size = sizeof(int);
// Allocate space for device copies of a, b, c
cudaMalloc((void **)&d_a, size);
cudaMalloc((void **)&d_b, size);
cudaMalloc((void **)&d_c, size);
// Setup input values
a = 2;
b = 7;
// Copy inputs to device
cudaMemcpy(d_a, &a, size, cudaMemcpyHostToDevice);
cudaMemcpy(d_b, &b, size, cudaMemcpyHostToDevice);
// Launch add() kernel on GPU
add<<<1,1>>>(d_a, d_b, d_c);
// Copy result back to host
cudaMemcpy(&c, d_c, size, cudaMemcpyDeviceToHost);
// Cleanup
cudaFree(d_a); cudaFree(d_b); cudaFree(d_c);
return 0;
}
test.go:
package main
import "fmt"
//#cgo CFLAGS: -I.
//#cgo LDFLAGS: -L. -ltest
//#cgo LDFLAGS: -lcudart
//#include <test.h>
import "C"
func main() {
fmt.Printf("Invoking cuda library...\n")
fmt.Println("Done ", C.test_add())
}
我正在编译 CUDA 代码:
nvcc -m64 -arch=sm_20 -o libtest.so --shared -Xcompiler -fPIC test.cu
所有三个文件 - test.h、test.cu 和 test.go 都位于同一目录中。
当我尝试使用 go 构建时遇到的错误是“对‘test_add’的未定义引用”。
我对 C/C++ 的经验很少,并且在 CUDA 方面完全是新手。
我已经尝试解决我的问题两天了
非常感谢您的任何意见。
Thanks.