Shishir kulkarni
Shishir kulkarni

Reputation: 31

how to pass stringized macros at arguments to gcc using -D option

I am compiling below code using the following command:
gcc test.c -D HEX=0xFFFF

#include <stdio.h>
#define NOERR 0
#define ERR 1

/*
 * Some Code 
 */
main()
{
    printf(#HEX);
}

I get the following output:

Ex2_03.c:33:9: error: stray ‘#’ in program
  printf(#HEX);
         ^
Ex2_03.c:33:2: warning: passing argument 1 of ‘printf’ makes pointer from integer without a cast [enabled by default]
  printf(#HEX);
  ^
In file included from Ex2_03.c:1:0:
/usr/include/stdio.h:362:12: note: expected ‘const char * __restrict__’ but argument is of type ‘int’
 extern int printf (const char *__restrict __format, ...);
            ^
Ex2_03.c:33:2: warning: format not a string literal and no format arguments [-Wformat-security]
  printf(#HEX);
  ^

Upvotes: 1

Views: 151

Answers (2)

lqhcpsgbl
lqhcpsgbl

Reputation: 3782

Your bug is the wrong way to use printf() and you can not define a variable starts with '#' :

#include <stdio.h>
#define NOERR 0
#define ERR 1

/*
 * Some Code
 */
int main()
{
    printf("%d",HEX);
    return 0;
}

Output:

zookeepdeMacBook-Pro:Desktop zookeep$ gcc hello.c  -D HEX=0xFFFF -o hello
zookeepdeMacBook-Pro:Desktop zookeep$ ./hello
65535

Upvotes: 1

ouah
ouah

Reputation: 145829

You got an error because # operator can only be used in a pre-processor directive.

You need to stringify your macro. Stringification requires a two levels macro:

#define STRINGIFY_(x)  #x
#define STRINGIFY(x)   STRINGIFY_(x)

printf(STRINGIFY(HEX));

Upvotes: 2

Related Questions