Hailiang Zhang
Hailiang Zhang

Reputation: 18930

How to declare a function outside of the class?

Here is the scenario:

I have some class functions that have to be compiled by some C++-derived compiler (CUDA nvcc). However, I need the class declaration to be compiled by regular C++ compiler. I know that a class function has to be declared inside the class declaration. Not sure how to bypass this problem. Thanks!

Say I have a file "a.cpp":

class A
{
  private:
    int i;
  public:
    __global__ int f() {return i;}
}

Here __global__ implies a CUDA kernel code that needs to be compiled by its specific compiler. However, I need "a.cpp" be compiled by regular C++ compiler.

I thought about using a wrapper that link against a kernel library built by CUDA compiler. However, the kernel need to reference the class private variable ("int i"), and I am trying to avoid passing them around.

Upvotes: 0

Views: 866

Answers (2)

Carlos Ch
Carlos Ch

Reputation: 403

I would suggest using a macro defenition:

#ifdef __CUDACC__
#define GLOBAL_CUDA __global__
#else
#define GLOBAL_CUDA
#endif

So when the CUDA compiler, gets the file it will see __global__ if it is a normal C++ compiler it will just see a blank space

class A
{
  private:
    int i;
  public:
    GLOBAL_CUDA int f() {return i;}
}

Upvotes: 2

Marc Claesen
Marc Claesen

Reputation: 17026

Implement the class member function as a wrapper of an extern function. You can then implement and compile the external function however you like.

In code:

extern "C"{
... quux(...);
}

class Foo{
public:
 ... bar(...){ return quux(...); }
}

Upvotes: 3

Related Questions