当前位置: 首页> 健康> 知识 > c++ 中检查 cuda 是否可用以及 cuda 版本

c++ 中检查 cuda 是否可用以及 cuda 版本

时间:2025/7/9 22:10:50来源:https://blog.csdn.net/weixin_43667077/article/details/139653051 浏览次数:0次

代码

main.cpp

#include <iostream>#ifdef HAVE_CUDA
#include <cuda_runtime.h>
#include <cuda.h>
#endifint main() {std::cout << "Checking CUDA availability..." << std::endl;#ifdef HAVE_CUDAint deviceCount = 0;cudaError_t error_id = cudaGetDeviceCount(&deviceCount);if (error_id != cudaSuccess) {std::cerr << "cudaGetDeviceCount returned " << static_cast<int>(error_id) << std::endl;std::cerr << "CUDA is not available." << std::endl;return 1;}if (deviceCount == 0) {std::cerr << "There is no device supporting CUDA." << std::endl;} else {std::cout << "CUDA is available. Version: " << CUDA_VERSION << std::endl;}
#elsestd::cerr << "CUDA is not available." << std::endl;
#endifreturn 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.10)
project(cuda_check)# Check for CUDA availability
find_package(CUDA)
if(CUDA_FOUND)add_definitions(-DHAVE_CUDA)include_directories(${CUDA_INCLUDE_DIRS})link_libraries(${CUDA_LIBRARIES})
endif()add_executable(cuda_check main.cpp)

输出说明

编译运行代码后,示例输出如下

Checking CUDA availability...
CUDA is available. Version: 11080

其中 11080 表示 cuda-11.8 版本

参考资料

How to Get CUDA Toolkit Version at Compile Time Without nvcc?
https://stackoverflow.com/questions/37970880/how-to-get-cuda-toolkit-version-at-compile-time-without-nvcc

【GPU】linux 安装、卸载 nvidia 显卡驱动、cuda 的官方文档、推荐方式(runfile)
https://blog.csdn.net/weixin_43667077/article/details/134813826

Ubuntu中多版本CUDA切换:
https://blog.csdn.net/sinat_40245632/article/details/109330182

关键字:c++ 中检查 cuda 是否可用以及 cuda 版本

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: