Rust compile C/Cuda

Viewed 129

I have an existing project in Rust / C and I want to migrate some low level hashing stuff to CUDA, but I can't get it to finish compiling.

I believe the compile part is working, as the error only appears in the linker if I call the function from the .cu file

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:

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
1 Answers

There was a linking problem as CUDA uses C++ linkage

The solution was to modify HelloWorld.h to

#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

There was no need to modify anything on HelloWorld.cu

Related