c++ - cuda和c++问题

标签 c++ cuda compilation static-linking

嗨,我有一个成功运行的 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/

相关文章:

c++ - 如何组合两个具有相同代码的模板函数?

java - 我们能否利用类型系统来使程序更加安全?

python - 在python或c++中使用sql根据输入数据输出输出样本

c++ - CUDA 错误 : "dynamic initialization is not supported for __device__, __constant__ and __shared__ variables"

tensorflow - 我已经安装了 CUDA 工具包,为什么 conda 又要安装 CUDA?

c - 将与输入 vector 相同的输出传递给 GEMV 以实现破坏性矩阵应用是否安全?

kotlin - 为什么无法访问的语句方法不会导致编译错误?

c++ - 错误 C2246 : cannot access private member

c++ - 有什么方法可以加速 gcc 中的宏预处理?

c++ - 编译和运行 C++ 代码运行时