Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a value to a variable at compilation time

Tags:

c++

c

gcc

I'd like to assign a specific value to a variable when my code is compiling (for C and C++):

For example having :

//test.c
int main()
{
   int x = MYTRICK ; (edit: changed __MYTRICK__ to MYTRICK to follow advices in comment)
   printf ("%d\n", x);

   return 0;
}

beeing able to do something like:

gcc -XXX MYTRICK=44 test.c -o test

and having as a result :

$./test
44
like image 307
IggY Avatar asked Jan 15 '23 11:01

IggY


1 Answers

Use -D option:

gcc -DMYTRICK=44 test.c -o test

And use MYTRICK macro in your program and not __MYTRICK__. Names beginning with __ are reserved by the implementation.

like image 82
ouah Avatar answered Jan 20 '23 02:01

ouah