Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use a cuda class header file in both cpp and cuda modules

Tags:

c++

cuda

I am trying to create Color object in my device. Here's a simplified version of what I have:

In Color.hpp:

class Color { 
public:
    Color(){}
    float r, g, b;
    // other functions
}

In test.cu:

__global__ void runCuda(){
    Color c = Color();
}

int main() {
   runCuda<<<1,1>>>()
}

This gives me an error saying that

calling a host function from a global function is not allowed

So this is fine. I simply need to add __host__ and __device__ in front of Color(){} function.

But then i get the following error:

host does not name a type

So from what I understand, this is happening because I am not compiling it with nvcc. The problem is I am using CMake to build my project. I am not too sure how it does it but it seems like it is compiling .cpp files with the c++ compiler and .cu with nvcc compiler.

But in my device, I want to create Color object. Is there a way to fix this either in my CMakefiles or in my code? Or do i need to create a cuda version for all my existing classes?

like image 474
MoneyBall Avatar asked Dec 14 '22 12:12

MoneyBall


1 Answers

Something like this should work:

#ifdef __CUDACC__
#define CUDA_HOSTDEV __host__ __device__
#else
#define CUDA_HOSTDEV
#endif

class Color { 
public:
    CUDA_HOSTDEV Color(){}
    float r, g, b;
    // other functions
};

When your hpp file is included in a .cu file, the __CUDACC__ macro will be defined. When it is included in a .cpp file (which nvcc hands off to the host compiler) the macro will not be defined.

like image 161
Robert Crovella Avatar answered May 18 '23 19:05

Robert Crovella