本人参考《基于GPU加速的计算机视觉编程》配置好CUDA 11.0的vs2017开发环境,创建了项目,并编译以下代码:
#include <iostream>
#include <cuda.h>
#include <cuda_runtime.h>
#include <stdio.h>
//Definition of kernel function to add two variables
__global__ void gpuAdd(int d_a, int d_b, int *d_c) {
*d_c = d_a + d_b;
}
//main function
int main(void) {
//Defining host variable to store answer
int h_c;
//Defining device pointer
int *d_c;
//Allocating memory for device pointer
cudaMalloc((void**)&d_c, sizeof(int));
//Kernel call by passing 1 and 4 as inputs and storing answer in d_c
//<< <1,1> >> means 1 block is executed with 1 thread per block
gpuAdd << <1, 2 >> > (1, 4, d_c);
//Copy result from device memory to host memory
cudaMemcpy(&h_c, d_c, sizeof(int), cudaMemcpyDeviceToHost);
printf("1 + 4 = %d\n", h_c);
//Free up memory
cudaFree(d_c);
return 0;
}
能够成功生成,但是结果不对,显示1+4=0。
经过查阅,将配置属性->CUDA C++ -> Device ->Code generation修改为如图所示:
修改的方法与显卡有关,显卡对应的Code generation的链接如下:
https://github.com/tpruvot/ccminer/wiki/Compatibility
我这儿是GeForce 930M的显卡,因此找到如下项:
修改完就可以得到正确的运算结果。
参考资料:
https://www.pianshen.com/article/7938867367/