macro function Is it impossible to use macro functions?

Hello, all

I’ve implemented several macro functions in .cu file which has cuda kernel function.

The kernel function and a device function called by kernel use that macro functions.

But when I compile it, all the macro functions cause errors.

The macro functions which I’ve defined are like below…

There are more complicated macro functions but I shorten them.

cuda global functions and device functions do not permit macro functions?

hello yeony102
you have such a good imagination for this kind of macro functions and i appreciate it but i think you had better white them separately for macro function just works as substitutions. and can you list the code behind your define works?

Actually those aren’t my imaginations.

I’m implementing the Tomas Moller’s algoritm, ‘A Fast Triangle-Triangle Intersection Test’.

And those macro functions are used on that algorithm :)

I happen to have used one of Moller’s algorithms in my CUDA once.
The macros get compiled without too much trouble. A big problem is those algorithms are written in portable C for CPU. A direct port may confuse nvcc with unresolvable use of pointers. It’s also rather under-optimized in a platform dependent sense. A rewrite in CUDA may be better than directly using the original source.

Could you post your .cu file? There probably is not enough context information here to determine the source of your problem.

My kernel source code is here.

Now, I’ve blocked the macro functions by comments.

And change some macro functions(which have a name consist of large characters) to device fuctions.

Then, the program works well.

But if I use macro functions, the program has errors.

I would have to see the version that actually generates errors to be of much help… one suggestion though which may or may not be relevant here…

Always surround the use of an argument in your macro with ()'s to protect from unexpected order of operation problems. Remember macros are more like “copy-replace” instead of an actual function call.

e.g.

use

#define F1(x) ((x) * (x))

instead of

#define F2(x) (x * x)
F1(a+b)

expands to

((a+b) * (a+b))

while

F2(a+b)

expands to

(a+b * a+b)

and also use the do-while(0)-construct for macros spaning several separate statements. Something like this:

#define CROSS(dest, v1, v2, i2, i1)
do
{
dest[0] = v1[i1*3+1]*v2[i2*3+2]-v1[i1*3+2]*v2[i2*3+1];
dest[1] = v1[i1*3+2]*v2[i2*3]-v1[i1*3]*v2[i2*3+2];
dest[2] = v1[i1*3]*v2[i2*3+1]-v1[i1*3+1]*v2[i2*3];
}
while(0)

I suggest that you do not use macros at all. They are awful to hack and have the usual scoping problems if the do…while trick isn’t used.

Turn them into proper device functions and the compiler will give you easy to check error messages if you write some bad code. The device functions get inlined anyway so there is no performance benefit for macros.

Peter

See more infomation in the nvcc guide.