Se Norm
Se Norm

Reputation: 1755

How to declare a function inside a kernel function in OpenCL?

I want to define a function within a kernel function to make my indexing code clearer:

kernel void do_something (const int some_offset,
                          const int other_offset,
                          global float* buffer)
{
    int index(int x, int y)
    {
        return some_offset+other_offset*x+y;
    }

    float value = buffer[index(1,2)];
    ...
}

Otherwise I'd have to declare the index function outside of my kernel and index like

float value = buffer[index(1,2,some_offset,other_offset)];

which would make it more ugly etc. Is there any way to do this? The compiler gives me an an error, saying:

OpenCL Compile Error: clBuildProgram failed (CL_BUILD_PROGRAM_FAILURE).
Line 5: error: expected a ";"

Is it possible to do what I want or is there a different way to achieve the same? Thanks!

Upvotes: 4

Views: 2000

Answers (1)

zvrba
zvrba

Reputation: 24546

C doesn't support nested functions. However, your case is simple enough to be implemented with a macro:

#define index(x,y) some_offset+other_offset*(x)+(y)

The parentheses around x and y are crucial to make the macro do what you want if you pass it more complicated expressions, e.g., index(a+b,c).

Upvotes: 5

Related Questions