5

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.

Community
  • 1
  • 1
Huarache
  • 246
  • 2
  • 13
  • 1
    I might be overlooking something, but what's stopping you from doing `-DHASH=hashfcn1` ? – MSalters Nov 20 '15 at 23:53
  • You're correct. I was kind of interested in supporting hash functions that take different numbers of arguments but where all but one are hard-coded constants, but that's easy enough to support by adding another function. – Huarache Nov 21 '15 at 00:08

3 Answers3

9
#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.

Ritesh
  • 1,809
  • 1
  • 14
  • 16
5

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
cup
  • 7,589
  • 4
  • 19
  • 42
2

Maybe not exactly what you want, but a simple way to achieve this is to generate an include file.

program.c:

#include "hash.h"
int y, x=0;
y = HASH(x);

and then your compilation does something like

echo '#define HASH(X) hashfunc1(X)' >hash.h
gcc -o program program.c

An advantage is that you can define HASH as something more elaborate than a call to a single-argument function. E.g. #define HASH(X) hashfunc1(X, other_complicated_arguments).

Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82