代码

main.cpp

#include <iostream>

#ifdef HAVE_CUDA
#include <cuda_runtime.h>
#include <cuda.h>
#endif

int main() {
    std::cout << "Checking CUDA availability..." << std::endl;

#ifdef HAVE_CUDA
    int 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;
    }
#else
    std::cerr << "CUDA is not available." << std::endl;
#endif

    return 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

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐