C++ 与 Cuda 混合编程的CMakeList 写法 与例子

11 篇文章 0 订阅
10 篇文章 0 订阅

前言

一般的情况下,C与Cuda混合编程,可能通过 VS的UI方式,创建工程。但是,这种情况下效率不高,并且不能跨平台。因此,高级的方式,是使用CMakeList的方式,创建工程。 Windows情况下,可以CMakeList 成VisualStudio 编译器。


CMakeList的模板

通常,可用的一个模板,整理如下:

CMakeList 文件

# required cmake version
cmake_minimum_required(VERSION 3.4)

project(test_cuda)

# packages
find_package(CUDA)

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

file(GLOB_RECURSE CURRENT_HEADERS  *.h *.hpp *.cuh)
file(GLOB CURRENT_SOURCES  *.cpp *.cu)

source_group("Include" FILES ${CURRENT_HEADERS}) 
source_group("Source" FILES ${CURRENT_SOURCES}) 

set(CMAKE_NVCC_FLAGS "CMAKE_NVCC_FLAGS -std=c++11")

CUDA_ADD_EXECUTABLE(test_cuda ${CURRENT_HEADERS} ${CURRENT_SOURCES})

特殊的地方:

  • find_package(CUDA) 寻找cuda的库
  • CUDA_ADD_EXECUTABLE(test_cuda ${CURRENT_HEADERS} ${CURRENT_SOURCES}) 生成可执行程序

测试的代码:

测试代码,分为 kernel.cu 的cuda 文件,以及C的主函数。

kernel.cu 文件

#include "cuda_runtime.h"
#include "device_launch_parameters.h"

#include <stdio.h>

__global__ void addKernel(int *c, const int *a, const int *b)
{
    int i = threadIdx.x;
    c[i] = a[i] + b[i];
}

// Helper function for using CUDA to add vectors in parallel.
extern "C"
cudaError_t addWithCuda(int *c, const int *a, const int *b, unsigned int size)
{
    int *dev_a = 0;
    int *dev_b = 0;
    int *dev_c = 0;
    cudaError_t cudaStatus;

    // Choose which GPU to run on, change this on a multi-GPU system.
    cudaStatus = cudaSetDevice(0);
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaSetDevice failed!  Do you have a CUDA-capable GPU installed?");
        goto Error;
    }

    // Allocate GPU buffers for three vectors (two input, one output)    .
    cudaStatus = cudaMalloc((void**)&dev_c, size * sizeof(int));
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMalloc failed!");
        goto Error;
    }

    cudaStatus = cudaMalloc((void**)&dev_a, size * sizeof(int));
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMalloc failed!");
        goto Error;
    }

    cudaStatus = cudaMalloc((void**)&dev_b, size * sizeof(int));
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMalloc failed!");
        goto Error;
    }

    // Copy input vectors from host memory to GPU buffers.
    cudaStatus = cudaMemcpy(dev_a, a, size * sizeof(int), cudaMemcpyHostToDevice);
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMemcpy failed!");
        goto Error;
    }

    cudaStatus = cudaMemcpy(dev_b, b, size * sizeof(int), cudaMemcpyHostToDevice);
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMemcpy failed!");
        goto Error;
    }

    // Launch a kernel on the GPU with one thread for each element.
    addKernel<<<1, size>>>(dev_c, dev_a, dev_b);

    // Check for any errors launching the kernel
    cudaStatus = cudaGetLastError();
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "addKernel launch failed: %s\n", cudaGetErrorString(cudaStatus));
        goto Error;
    }
    
    // cudaDeviceSynchronize waits for the kernel to finish, and returns
    // any errors encountered during the launch.
    cudaStatus = cudaDeviceSynchronize();
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaDeviceSynchronize returned error code %d after launching addKernel!\n", cudaStatus);
        goto Error;
    }

    // Copy output vector from GPU buffer to host memory.
    cudaStatus = cudaMemcpy(c, dev_c, size * sizeof(int), cudaMemcpyDeviceToHost);
    if (cudaStatus != cudaSuccess) {
        fprintf(stderr, "cudaMemcpy failed!");
        goto Error;
    }

Error:
    cudaFree(dev_c);
    cudaFree(dev_a);
    cudaFree(dev_b);
    
    return cudaStatus;
}

main.cpp 文件:


#include <stdio.h>
#include "cuda_runtime.h"
#include "device_launch_parameters.h"

extern "C" cudaError_t addWithCuda(int *c, const int *a, const int *b, unsigned int size);

int main()
{
	const int arraySize = 5;
	const int a[arraySize] = { 1, 2, 3, 4, 5 };
	const int b[arraySize] = { 10, 20, 30, 40, 50 };
	int c[arraySize] = { 0 };
 
	// Add vectors in parallel.
	cudaError_t cudaStatus = addWithCuda(c, a, b, arraySize);
	if (cudaStatus != cudaSuccess) {
		fprintf(stderr, "addWithCuda failed!");
		return 1;
	}
 
	printf("{1,2,3,4,5} + {10,20,30,40,50} = {%d,%d,%d,%d,%d}\n",
		c[0], c[1], c[2], c[3], c[4]);
	printf("cuda工程中调用cpp成功!\n");
 
	// cudaDeviceReset must be called before exiting in order for profiling and
	// tracing tools such as Nsight and Visual Profiler to show complete traces.
	cudaStatus = cudaDeviceReset();
	if (cudaStatus != cudaSuccess) {
		fprintf(stderr, "cudaDeviceReset failed!");
		return 1;
	}
	getchar(); //here we want the console to hold for a while
	return 0;
}

测试结果:

{1,2,3,4,5} + {10,20,30,40,50} = {11,22,33,44,55}
cuda工程中调用cpp成功!

测试的例子,是直接从其它的网站上拿过来的。比较能够说明 cMakeLists.txt 作用。


引用:

c++ 和cuda混合编程 VS2015 C++ 调用 cuda

  • 3
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的示例,展示如何在VSCode中使用C和C++混合编程: ```c++ #include <stdio.h> extern "C" { #include "myCFile.h" // 包含C文件的头文件 } int main() { int a = 10; int b = 20; int result = add(a, b); // 调用C函数 printf("The result is: %d\n", result); return 0; } ``` 这里,我们在C++代码中使用`extern "C"`关键字,告诉编译器这是一个C语言函数。然后,在`main()`函数中,我们调用了一个C函数`add()`,该函数在`myCFile.h`头文件中声明。 在VSCode中,我们可以使用C/C++扩展来编译和运行此代码。在`.vscode`文件夹中创建一个`tasks.json`文件,指定编译器和编译选项: ```json { "version": "2.0.0", "tasks": [ { "label": "gcc build", "type": "shell", "command": "gcc", "args": [ "-g", "-Wall", "-o", "${fileDirname}/${fileBasenameNoExtension}.out", "${file}" ], "group": { "kind": "build", "isDefault": true }, "presentation": { "echo": true, "reveal": "silent", "focus": false, "panel": "shared" }, "problemMatcher": { "owner": "cpp", "fileLocation": ["absolute"], "pattern": { "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$", "file": 1, "line": 2, "column": 3, "severity": 4, "message": 5 } } } ] } ``` 然后,我们可以使用`Ctrl+Shift+B`快捷键来编译代码,并使用`F5`来运行代码。 注意:如果您的C文件中包含了C++标准库头文件(如`<iostream>`),则需要将C文件的扩展名更改为`.cpp`,以便C++编译器能够正确识别它。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值