Friday, September 20, 2013

Complex Macro Define

How do you indicate a macro define on the compile line that contains white spaces and double quotes?

Let's start with someting simple

vi defn.cxx
#include <stdio.h>
int main()
{
  printf("hello world\n");
  return 0;
}
# g++ defn.cxx -o defn.exe
# ./defn.exe
hello world

We can do the same thing with an inline define:

#include <stdio.h>
#define mydefine printf("hello world\n");
int main()
{
  mydefine
  return 0;
}
# g++ defn.cxx -o defn.exe
# ./defn.exe
hello world

We can provide simple defines on the command line:

#include <stdio.h>
int main()
{
  mydefine("hello world\n");
  return 0;
}
# g++ -Dmydefine=printf defn.cxx -o defn.exe
# ./defn.exe
hello world

By using double quotes, we can provide defines on the command line that contain whitespace:

#include <stdio.h>
mydefine()
{
  printf("hello world\n");
  return 0;
}
# g++ -Dmydefine="int main" defn.cxx -o defn.exe
# ./defn.exe
hello world

By escaping the double quotes, we can provide defines on the command line that contain both whitespace and double quotes. Note that the \ itself in our \n also needs to be escaped.

#include <stdio.h>
int main()
{
  mydefine
  return 0;
}
# g++ -Dmydefine="printf(\"hello world\\n\");" defn.cxx -o defn.exe
# ./defn.exe
hello world
c++
{ "loggedin": false, "owner": false, "avatar": "", "render": "nothing", "trackingID": "UA-36983794-1", "description": "", "page": { "blogIds": [ 450 ] }, "domain": "holtstrom.com", "base": "\/michael", "url": "https:\/\/holtstrom.com\/michael\/", "frameworkFiles": "https:\/\/holtstrom.com\/michael\/_framework\/_files.4\/", "commonFiles": "https:\/\/holtstrom.com\/michael\/_common\/_files.3\/", "mediaFiles": "https:\/\/holtstrom.com\/michael\/media\/_files.3\/", "tmdbUrl": "http:\/\/www.themoviedb.org\/", "tmdbPoster": "http:\/\/image.tmdb.org\/t\/p\/w342" }