当我尝试在内核中使用printf()时出错

时间:2013-02-12 13:13:49

标签: cuda

我正在使用Visual Studio 2010和具有计算能力2.0的GTX480。

我尝试将sm设置为2.0,但是当我尝试在内核中使用printf()时,我得到:

  

错误:从__device __ / __ global__调用主机函数(“printf”)   不允许使用函数(“test”)

这是我的代码:

#include "util\cuPrintf.cu"
#include <cuda.h>
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <cuda_runtime.h>

__global__ void test (void)
{
  printf("Hello, world from the device!\n");
}

void main(void)
{
    test<<<1,1>>>();
    getch();
}

我在这里找到一个例子:“CUDA_C_Programming_Guide”'page _106'“B.16.4例子” 最后,这对我有用:D谢谢。

#include "stdio.h"
#include <conio.h>

// printf() is only supported
// for devices of compute capability 2.0 and higher

  #if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 200)
      #define printf(f, ...) ((void)(f, __VA_ARGS__),0)
  #endif


__global__ void helloCUDA(float f)
{
    printf("Hello thread %d, f=%f\n", threadIdx.x, f);
}

int main()
{
    helloCUDA<<<1, 5>>>(1.2345f);
    cudaDeviceSynchronize();
    getch();
    return 0;
}

3 个答案:

答案 0 :(得分:3)

要在内核代码中使用printf,您必须做三件事:

  1. 确保内核编译单元中包含cstdiostdio.h。 CUDA通过重载实现内核printf,因此您必须包含该文件
  2. 编译计算能力2.x或3.x的代码并在支持的GPU上运行(因此将-arch=sm_20传递给nvcc或Visual Studio或Nsight Eclipse版本中的等效IDE)
  3. 通过在主机代码中包含显式或隐式同步点(例如cudaDeviceSynchronize),确保内核已完成运行。

答案 1 :(得分:1)

您可能正在编译不支持printf()的体系结构。默认情况下,项目是针对计算体系结构1.0编译的。要更改此项,请在VS中打开项目属性 - &gt; CUDA C / C ++ - &gt;设备并将“代码生成”属性更改为“compute_20,sm_20”。

您不需要#include "util\cuPrintf.cu"。有关如何使用printf以及如何刷新输出的详细信息,请参阅this

答案 2 :(得分:0)

如果您收到该错误,则可能意味着您的GPU没有2.x或更高的计算能力。 This thread详细介绍了在内核函数中打印的选项。

相关问题