CUDA by examples第四章源代码错误处理方案

学习cuda,使用了这本书,第四章的源代码怎么也编译通过不了

在网上查了很多资料,花了一个晚上的时间死磕,终于通了

鉴于我几乎是遇见了网上各种资料里能够出现的所有问题,我准备做一个编译错误合集总结一下一个晚上的成果。

1、代码问题

本章的代码是有问题的,要把cuComplex()构造函数前面加上__device__,正确代码如下

#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include "../common/book.h"
#include "../common/cpu_bitmap.h"
//#include "stdio.h"
#define DIM 500
cudaError_t addWithCuda(int *c, const int *a, const int *b, unsigned int size);

__device__ struct cuComplex {
	float   r;
	float   i;
	__device__ cuComplex(float a, float b) : r(a), i(b) {}
	__device__ float magnitude2(void) {
		return r * r + i * i;
	}
	__device__ cuComplex operator*(const cuComplex& a) {
		return cuComplex(r*a.r - i*a.i, i*a.r + r*a.i);
	}
	__device__ cuComplex operator+(const cuComplex& a) {
		return cuComplex(r + a.r, i + a.i);
	}
};
__device__ int julia(int x, int y) {
	const float scale = 1.5;
	float jx = scale * (float)(DIM / 2 - x) / (DIM / 2);
	float jy = scale * (float)(DIM / 2 - y) / (DIM / 2);

	cuComplex c(-0.8, 0.156);
	cuComplex a(jx, jy);

	int i = 0;
	for (i = 0; i<200; i++) {
		a = a * a + c;
		if (a.magnitude2() > 1000)
			return 0;
	}

	return 1;
}


__global__ void kernel(unsigned char *ptr) {
	// map from blockIdx to pixel position
	int x = blockIdx.x;
	int y = blockIdx.y;
	int offset = x + y * gridDim.x;

	// now calculate the value at that position
	int juliaValue = julia(x, y);
	ptr[offset * 4 + 0] = 255 * juliaValue;
	ptr[offset * 4 + 1] = 0;
	ptr[offset * 4 + 2] = 0;
	ptr[offset * 4 + 3] = 255;
}

struct DataBlock {
	unsigned char   *dev_bitmap;
};

int main(void)
{
	DataBlock   data;
	CPUBitmap bitmap(DIM, DIM, &data);
	unsigned char    *dev_bitmap;

	HANDLE_ERROR(cudaMalloc((void**)&dev_bitmap, bitmap.image_size()));
	data.dev_bitmap = dev_bitmap;

	dim3    grid(DIM, DIM);
	kernel << <grid, 1 >> >(dev_bitmap);

	HANDLE_ERROR(cudaMemcpy(bitmap.get_ptr(), dev_bitmap,
		bitmap.image_size(),
		cudaMemcpyDeviceToHost));

	HANDLE_ERROR(cudaFree(dev_bitmap));

	bitmap.display_and_exit();
}

此时会显示找不到头文件,要把头文件加到编译路径下(也就是把common文件夹粘到文件夹里)

2、环境问题
环境配置是蛮令人头疼的
1)解决方案设置更改
显示各种库函数找不到——配置属性>>常规>>windows SDK版本>>(8.1改到10.0.16299.0)
显示找不到glut64.lib——VC++目录>>库目录>>添加装有glut64.lib的文件夹
2 ) 动态链接库设置
显示找不到glut64.dll——将.dll文件放入系统盘Windows目录下的两个文件内(c://windows/system32和syswow64)
3、代码继续更改
编译代码,bitmap图还是不出现。。可能是DIM设置的过大了,改成500就可以了



参考博客:
http://blog.csdn.net/zpb312/article/details/71524950
http://blog.csdn.net/qq_25071449/article/details/77713592








猜你喜欢

转载自blog.csdn.net/weiwanshu/article/details/78527182