I was wondering if it's possible to pass macros that take arguments on the compile line to gcc or other C/C++ compilers.
I've never seen this before, but it would actually be useful for some of the OpenCL development that I've been doing where I want to replace a function name with a macro that can replaced at compile time.
Below is an example:
int y, x = 0;
y = HASH(x);
It would be nice if it were possible to define HASH as a macro on the compile line, so that when I compile the program, I could redefine HASH as necessary. For instance, it would be awesome if I could do gcc -DHASH(X)=(hash_fcn1(X)) program.c -o program
, but I've never seen this kind of thing before.
I've tried it with clBuildProgram but with no luck.
I realize that I could just have another program that passes over the program and substitutes the correct function name in for HASH, but I'm wondering if there's an easy way to do this without using a tool like sed, awk, or a string substitution or regex library in my language of choice.
Another solution would be to define a flat macro on the command line, and then have a series of guards in the actual source file that control how the macro gets defined in the source file, e.g. like in this other post how to compare string in C conditional preprocessor-directives.
Passing parameters to a macro. A parameter can be either a simple string or a quoted string. It can be passed by using the standard method of putting variables into shared and profile pools (use VPUT in dialogs and VGET in initial macros).
Macros are expanded prior to the code being parsed/compiled as C. You can pass it to a macro function.
A parameterized macro is a macro that is able to insert given objects into its expansion. This gives the macro some of the power of a function. As a simple example, in the C programming language, this is a typical macro that is not a parameterized macro: #define PI 3.14159.
Macro Arguments (DEFINE-! ENDDEFINE command) The macro definition can include macro arguments, which can be assigned specific values in the macro call. There are two types of arguments: keyword and positional. Keyword arguments are assigned names in the macro definition; in the macro call, they are identified by name.
#include <stdio.h>
int func2(int x) {
return x+1;
}
int func1(int x) {
return x+2;
}
int main()
{
int x = 0;
int y = HASH(x);
printf("x=%d\n", y);
return 0;
}
I wrote the above code and I compiled with : gcc -O0 -DHASH=func1 -o test test.c and gcc -O0 -DHASH=func2 -o test test.c
And I got output 1 and 2. I think the important thing to notice is that I have not #defined HASH anywhere in the code.
The macro should be defined without parameters.
gcc -DHASH=hash_fcn1 program.c -o program
If you wish to pass parameters, the brackets need to be escaped
gcc -DHASH\(X\)=hash_fcn1\(X,55u,33u\) program.c -o program
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With