Rust 编译 C/Cuda

Rust compile C/Cuda

我在 Rust / C 中有一个现有项目,我想将一些低级散列的东西迁移到 CUDA,但我无法完成编译。

我相信编译部分工作正常,因为如果我从 .cu 文件调用函数,错误只会出现在链接器中

build.rs

fn main() {
    let mut cfg = cc::Build::new();
    cfg.cuda(true);
    cfg.include("project/include")
        .include("project/src")
        .file("project/src/HelloWorld.cu")
        .file("project/src/Validate.c")
        //more C files...
        .out_dir(dst.join("lib"))
        .flag("-O2")
        .compile("libproject.a");

    println!("cargo:root={}", dst.display());
    println!("cargo:include={}", dst.join("include").display());
    println!(
        "cargo:rerun-if-changed={}",
        env::current_dir().unwrap().to_string_lossy()
    );
    println!("cargo:rerun-if-env-changed=PC_CC");

    if let Ok(cuda_path) = env::var("CUDA_HOME") {
        println!("cargo:rustc-link-search=native={}/lib64", cuda_path);
    } else {
        println!("cargo:rustc-link-search=native=/usr/local/cuda/lib64");
    }
    println!("cargo:rustc-link-lib=dylib=cudart");
}

HelloWorld.h

#ifndef CUDA_HELLO_WORLD_H
#define CUDA_HELLO_WORLD_H

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

void cudaTest();

#endif

HelloWorld.cu

#include "HelloWorld.h"


__global__ void mykernel(void){

}

void cudaTest(){
    mykernel<<<1,1>>>();
    printf("Hello World!\n");
}

错误:

error: linking with `cc` failed: exit status: 1
[...] really big compile command
= note: /usr/bin/ld: project/target/debug/deps/libproject-673a2f9d363593e3.rlib(File.o): in function `call_to_cuda_file`:
project/project/src/File.c:168: undefined reference to `cudaTest`
collect2: error: ld returned 1 exit status

CUDA 使用 C++ 链接时出现链接问题

解决方案是将HelloWorld.h修改为

#ifndef CUDA_HELLO_WORLD_H
#define CUDA_HELLO_WORLD_H

#ifdef __cplusplus
extern "C"
{
#endif

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

void cudaTest();

#ifdef __cplusplus
}
#endif

#endif

不需要在 HelloWorld.cu

上修改任何内容