嗨,我有一个成功运行的 cuda 程序 这是cuda程序的代码
#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? 如何
最佳答案
具有 CUDA C 扩展名的代码必须在 *.cu 文件中,其余可以在 c++ 文件中。
所以在这里您的内核代码可以移动到单独的 *.cu 文件。
要在 c++ 文件中实现主要功能,您需要使用 c++ 函数包装内核调用(带有 square_array<<<...>>>(...);
的代码),该实现也需要在 *cu 文件中。
函数 cudaMalloc 等可以保留在 c++ 文件中,只要您包含适当的 cuda header 。
关于c++ - cuda和c++问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5322581/