2011-03-16 30 views
0

您好我有哪些成功运行 CUDA程序这里是CUDA程序代码CUDA和C++的问题

#include <stdio.h> 
#include <cuda.h> 

    __global__ void square_array(float *a, int N) 
    { 
     int idx = blockIdx.x * blockDim.x + threadIdx.x; 
     if (idx<N) 
     a[idx] = a[idx] * a[idx]; 
    } 

    int main(void) 
    { 
     float *a_h, *a_d; 
     const int N = 10; 
     size_t size = N * sizeof(float); 
     a_h = (float *)malloc(size);   
     cudaMalloc((void **) &a_d, size); 
     for (int i=0; i<N; i++) a_h[i] = (float)i; 
     cudaMemcpy(a_d, a_h, size, cudaMemcpyHostToDevice); 
     int block_size = 4; 
     int n_blocks = N/block_size + (N%block_size == 0 ? 0:1); 
     square_array <<< n_blocks, block_size >>> (a_d, N); 

     cudaMemcpy(a_h, a_d, sizeof(float)*N, cudaMemcpyDeviceToHost); 
     // Print results 
     for (int i=0; i<N; i++) printf("%d %f\n", i, a_h[i]); 

     free(a_h); 
     cudaFree(a_d); 
    } 

现在我想这段代码分为两个文件意味着应该有两个文件,一个用于C++代码或c代码和其他一个.cu文件的内核。我只是想为了学习而做,而且我不想一次又一次地写同样的内核代码。 任何人都可以告诉我该怎么做? 如何将这段代码分成两个不同的文件? 比如何编译它? 如何为它编写makefile? 如何到

回答

1

有CUDA C扩展的代码必须在* .cu文件中,其余的可以在C++文件中。

所以这里你的内核代码可以移动到单独的* .cu文件。

要在C++文件中实现主函数,您需要用C++函数来包装内核的调用(代码为square_array<<<...>>>(...);),而实现需要在* cu文件中。

函数cudaMalloc等可以留在C++文件中,只要你包含适当的cuda头文件。

+0

thax的帮助我动了我的kenel代码到seprate文件名squre .CU#包括 的#include __global__无效square_array(浮动*一,INT N) { int idx = blockIdx.x * blockDim.x + threadIdx。X; if(idx user513164 2011-03-16 09:10:18

0

你最可能遇到的最大障碍是 - 如何从你的cpp文件调用你的内核。 C++不会理解你的<<< >>>语法。有3种方式。

  • 只写一个小封装主机功能在您的.cu文件

  • 使用CUDA库函数(cudaConfigureCallcudaFuncGetAttributescudaLaunch)---检查细节Cuda的参考手册,章节 “执行控制” online version 。只要包含cuda库,您就可以在纯C++代码中使用这些函数。

  • 在运行时包含PTX。这很难,但允许您在运行时操作PTX代码。这种JIT方法CUDA编程指南中解释(章3.3.2)和Cuda的参考手册(模块管理一章)online version


Encapsilating功能可能看起来像这样的例子:

的MyStuff .CU:

... //your device square_array function 

void host_square_array(dim3 grid, dim3 block, float *deviceA, int N) { 
    square_array <<< grid, block >>> (deviceA, N); 
} 

mystuff.h

#include <cuda.h> 
void host_square_array(dim3 grid, dim3 block, float *deviceA, int N); 

mymain.cpp

#include "mystuff.h" 

int main() { ... //your normal host code 
} 
+0

thankx为你的帮助,请你可以解释我是如何写一个小的封装主机功能在亩.cu?我应该怎么把我的.cu和如何complile和链接我的程序 – user513164 2011-03-16 09:16:17

+0

user513164:看看这篇文章是否有用看到.cu和C++分离:http://gpucoder.livejournal.com/2949.html – 2011-03-16 09:48:36

+0

thanx forhelp我只是这样做,现在我不知道如何将它编译出来,你可以解释我 – user513164 2011-03-16 09:52:33