使用qt cmake构建cuda程序

为了编写cuda程序,本文使用Qt作为IDE,使用cmake构建程序
pro文件如下:

project(CudaWithQt)
cmake_minimum_required(VERSION 2.8)

#packages
#找到cuda的库 可以通过cmake --help-module-list查看可以看到FINDCUDA
find_package(CUDA REQUIRED)

#nvcc flags
set(CUDA_NVCC_FLAGS -gencode arch=compute_20,code=sm_20;-G;-g)

#将要编译的文件,赋值给CURRENT_XX变量
file(GLOB_RECURSE CURRENT_HEADERS  *.h *.hpp *.cuh)
file(GLOB CURRENT_SOURCES  *.cpp *.cu)

#构建程序
CUDA_ADD_EXECUTABLE(test_cuda_project ${CURRENT_HEADERS} ${CURRENT_SOURCES})

kernel.cu

// CUDA-C includes
#include 

#include 

#include 

extern "C" void runCudaPart();


__global__ void addAry( int * ary1, int * ary2 )
{
    int indx = threadIdx.x;
    ary1[ indx ] += ary2[ indx ];
}


// Main cuda function

void runCudaPart() {

    int ary1[32];
    int ary2[32];
    int res[32];

    for( int i=0 ; i<32 ; i++ )
    {
        ary1[i] = i;
        ary2[i] = 2*i;
        res[i]=0;
    }

    int * d_ary1, *d_ary2;
    cudaMalloc((void**)&d_ary1, 32*sizeof(int));
    cudaMalloc((void**)&d_ary2, 32*sizeof(int));


    cudaMemcpy((void*)d_ary1, (void*)ary1, 32*sizeof(int), cudaMemcpyHostToDevice);
    cudaMemcpy((void*)d_ary2, (void*)ary2, 32*sizeof(int), cudaMemcpyHostToDevice);


    addAry<<<1,32>>>(d_ary1,d_ary2);

    cudaMemcpy((void*)res, (void*)d_ary1, 32*sizeof(int), cudaMemcpyDeviceToHost);
    for( int i=0 ; i<32 ; i++ )
        printf( "result[%d] = %d\n", i, res[i]);


    cudaFree(d_ary1);
    cudaFree(d_ary2);
}

main.cpp

#include 
extern "C"
void runCudaPart();

int main(int argc, char *argv[])
{
    runCudaPart();
}

你可能感兴趣的:(c++学习笔记)