3

The purpose of this is to build a program with command line-injected macros, using a Makefile.

I would like to define macros using multiple terms, however I am given an error as subsequent parts of the string are treated as files by gcc.

An example of what I need is as follows:

#define ULL unsigned long long
#define T_ULL typedef unsigned long long ull_t

As a result, I am only able to create macros that contain 1 term per definition.

The latter attempt allows me to create parameterized macros, however those are also limited to 1 term per definition.


Attempted solution

#include <stdio.h>
#define _STRINGIZE(x)   #x
#define STRINGIZE(x)    _STRINGIZE(x)

int main(void)
{
#   ifdef DEBUG
    #   ifdef STRING
            printf("%s", "A STRING macro was defined.\n");
            printf("string: %s\n", STRINGIZE(STRING));
    #   else
            printf("%s\n", "A DEBUG macro was defined.");
    #   endif
#   endif
}

Results

As described by the man page, under the -D option description.

$ gcc define.c -D='DEBUG' ; ./a.out
A DEBUG macro was defined.

As described by this answer, as an alternative approach.

$ gcc define.c -D'DEBUG' ; ./a.out
A DEBUG macro was defined.
$ gcc define.c -D'DEBUG' -D'STRING="abc"' ; ./a.out
A STRING macro was defined.
string: "abc"
$ gcc define.c -D'DEBUG' -D'STRING="abc efg"' ; ./a.out
clang: error: no such file or directory: 'efg"'
A STRING macro was defined.
string: "abc"
$ gcc define.c -D'DEBUG' -D'STRING="abc efg hij"' ; ./a.out
clang: error: no such file or directory: 'efg'
clang: error: no such file or directory: 'hij"'
A DEBUG macro was defined.
string: "abc"
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128

1 Answers1

3

You don't need the STRINGIZE macro. The correct command-line syntax is:

gcc -DDEBUG -DSTRING='"abc def"' program.c

In other words, you need to quote the whole value of the defined macro, including C string delimiters (").

Then you can just do:

printf("string: %s\n", STRING);
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
  • Thanks! I was also able to do `gcc program.c -D'DEBUG' -D'STRING="abc def"'` which works as well. For some reason, the string was being broken up by the shell. – Victor Wade Jan 19 '20 at 19:18