http://www.cmake.org/
下载了最新的cmake,调用了里面的一个FindCUDA.cmake,完成了自己的第一次使用cmake编译cuda代码。具体步骤如下:
1.下载最新版的cmake(其实只要有FindCUDA.cmake这个文件,你就可以编译cuda与c或者c++混合的代码文件了)
2.因为初次测试,所以我把所有的文件都放在同一个文件夹下面:c_cpp_cu1.cu;c_cpp_cu3.cpp两个源文件加一个CMakeLists.txt文件;
3.CmakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
PROJECT(test_cuda)
INCLUDE(/..../Downloads/cmake-3.2.2-Linux-x86_64/share/cmake-3.2/Modules/FindCUDA.cmake)
CUDA_ADD_EXECUTABLE(test_cuda
c_cpp_cu3.cpp
c_cpp_cu1.cu)
4.c_cpp_cu3.cpp
#include <iostream>
using namespace std;
extern "C" int func(); //注意这里的声明
int main()
{
func();
return 0;
}
5.c_cpp_cu1.cu
#include <stdio.h>
#include <stdlib.h>
#include <cuda_runtime.h>
#define ROWS 32
#define COLS 16
#define CHECK(res) if(res!=cudaSuccess){exit(-1);}
__global__ void Kerneltest(int **da, unsigned int rows, unsigned int cols)
{
unsigned int row = blockDim.y*blockIdx.y + threadIdx.y;
unsigned int col = blockDim.x*blockIdx.x + threadIdx.x;
if (row < rows && col < cols)
{
da[row][col] = row*cols + col;
}
}
extern "C" int func() // 注意这里定义形式
{
int **da = NULL;
int **ha = NULL;
int *dc = NULL;
int *hc = NULL;
cudaError_t res;
int r, c;
bool is_right=true;
res = cudaMalloc((void**)(&da), ROWS*sizeof(int*));CHECK(res)
res = cudaMalloc((void**)(&dc), ROWS*COLS*sizeof(int));CHECK(res)
ha = (int**)malloc(ROWS*sizeof(int*));
hc = (int*)malloc(ROWS*COLS*sizeof(int));
for (r = 0; r < ROWS; r++)
{
ha[r] = dc + r*COLS;
}
res = cudaMemcpy((void*)(da), (void*)(ha), ROWS*sizeof(int*), cudaMemcpyHostToDevice);CHECK(res)
dim3 dimBlock(16,16);
dim3 dimGrid((COLS+dimBlock.x-1)/(dimBlock.x), (ROWS+dimBlock.y-1)/(dimBlock.y));
Kerneltest<<<dimGrid, dimBlock>>>(da, ROWS, COLS);
res = cudaMemcpy((void*)(hc), (void*)(dc), ROWS*COLS*sizeof(int), cudaMemcpyDeviceToHost);CHECK(res)
for (r = 0; r < ROWS; r++)
{
for (c = 0; c < COLS; c++)
{
printf("%4d ", hc[r*COLS+c]);
if (hc[r*COLS+c] != (r*COLS+c))
{
is_right = false;
}
}
printf("\n");
}
printf("the result is %s!\n", is_right? "right":"false");
cudaFree((void*)da);
cudaFree((void*)dc);
free(ha);
free(hc);
// getchar();
return 0;
}
完成,生成一大堆文件+test_cuda的可执行文件