CUDA-为什么无法以cuda代码打印信息? [重复]

问题描述 投票:0回答:1

我是cuda的初学者。我写了一个测试代码来测试GPU设备。我的gpu模型是k80。

[一个节点中有8个GPU卡。

#include <iostream>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>

#define N 10000

__global__ void add(int *a, int *b, int *c)
{
  int tid = blockIdx.x;
  if (tid < N)
   c[tid] = a[tid] + b[tid];
}

int main()
{
 int a[N], b[N], c[N];
 int *dev_a, *dev_b, *dev_c;
 cudaMalloc((void**)&dev_a, N * sizeof(int));
 cudaMalloc((void**)&dev_b, N * sizeof(int));
 cudaMalloc((void**)&dev_c, N * sizeof(int));

 for (int i = 0;i < N;i++)
 {
  a[i] = -i;
  b[i] = i*i;
 }

 cudaMemcpy(dev_a, a, N * sizeof(int), cudaMemcpyHostToDevice);
 cudaMemcpy(dev_b, b, N * sizeof(int), cudaMemcpyHostToDevice);

 add << <N, 1 >> > (dev_a, dev_b, dev_c);
 cudaMemcpy(c, dev_c, N * sizeof(int), cudaMemcpyDeviceToHost);

for (int i = 0;i < N;i++)
{
    printf("%d + %d = %d\\n", a[i], b[i], c[i]);
}

   cudaFree(dev_a);
   cudaFree(dev_b);
   cudaFree(dev_c);

   return 0;
}

当我编译代码时:

 nvcc gputest.cu  -o gputest

我有错误:

 gputest.cu(38): error: identifier "printf" is undefined
 1 error detected in the compilation of "/tmp/tmpxft_000059a6_00000000-4_gputest.cpp4.ii".

我认为printf是iostream文件中的一个函数,但是我已经包含了iostream。我不知道为什么?

cuda
1个回答
1
投票

添加:

 #include <stdio.h>

它将编译就可以了。

printf是函数defined in the C standard library cstdio,因此在这里包含stdio.h是有意义的。不同的编译器在这里可能会有不同的行为,但是对于nvcc,这通常是正确的方法。

(在所有情况下都不能认为包含iostream将满足此处的引用。)

© www.soinside.com 2019 - 2024. All rights reserved.