15. December 2011

How to define C++ macro with string content and pass it to MSbuild

Imagine that we have C++ project e.g. for Visual Studio 2008. It is possible to build this project just by msbuild command:

msbuild MyProject.vcproj /p:Configuration="Release"

Let say that we want to use #define in the source code. It is necessary to define it in Configuration Properties > C++ > Command Line:

/DSIMPLE_DEFINE

This just pass SIMPLE_DEFINE as flag.

How to deal with string define which should behave like string? E.g.:

#define URL "https://georgik.rocks"

The trick is in escaping quotes. We can add following define to Command Line:

/DURL=\"https://georgik.rocks\"

It will transform into .vcproj file:

AdditionalOptions="/DURL=\"https://georgik.rocks\""

Let’s make one more step.

How to acquire such a define from environment variable? E.g. with following build.bat file:

set URL="https://georgik.rocks"
msbuild MyProject.vcproj /p:Configuration="Release"

It requires only small modification of .vcproj file:

AdditionalOptions="/DURL=\"$(URL)\""

;-)

Small recap of flow: set env variable – pass it to XML – pass it compiler – pass it to code