1

I have a simple cpp file as following on Unix environment:

#include <stdio.h>
#ifndef HELLO
    #define HELLO    "hello"
#endif

int main()
{
    printf("HELLO = %s \n", HELLO);
    return 0;
}

If this was compiled and ran, it prints out HELLO = HELLO.

However, when I do export HELLO="HELLO", then compile the program using g++ -Wall -g -DHELLO, I get a warning saying:

    warning: format ‘%s’ expects argument of type ‘char*’, but argument 2 has type     ‘int’ [-Wformat=]
         printf("HELLO = %s \n", HELLO);

When I run the program, I get a segmentation fault.

How would I print -DHELLO in the code?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Byung Kim
  • 21
  • 5
  • 2
    `-DHELLO` is equivalent to `#define HELLO 1`, hence you get incorrect code. You need to do `'-DHELLO="hello"'` (you can check this by directly invoking preprocessor `cpp`: `echo 'HELLO' | cpp -DHELLO`) – myaut Oct 02 '17 at 23:41

1 Answers1

1

-DHELLO is equivalent to #define HELLO 1, which explains the compilation error, which complaints about an int, rather than a char*.

Try compiling like this:

g++ -Wall -g -DHELLO="hello"
gsamaras
  • 71,951
  • 46
  • 188
  • 305