wrgrs
wrgrs

Reputation: 2569

Pass string macro into C program - cross-platform

I need to pass a string value into my C program at compile time:

-DNAME=value

I know of two ways to do this: Stringification as described here: https://gcc.gnu.org/onlinedocs/cpp/Stringification.html

#define xstr(s) str(s)
#define str(s) #s
...
printf("%s\n", xstr(NAME));

The problem I have here is that macros inside the string are substituted, so as my string contains -linux- it becomes -1- on linux.

The other way is to try to quote the string correctly when passing. I'm doing this from a Python setup.py file as follows:

macros = [('NAME', '"value"')]

or equivalently

-DNAME='"value"'

Then I just

printf("%s\n", NAME);

But I can't find a way to do this correctly both on Linux (gcc) and Windows (MSVC 9 for Python 2.7).

This may be complicated by the fact that the string may contain /, \ or % and so I need to do some escaping.


Let's bring this back to setup.py, which is where this needs to work.

value = '"value"'   # works on Linux but not Windows
value = '\\"value\\"'   # works on Windows but not Linux

Upvotes: 3

Views: 202

Answers (1)

wrgrs
wrgrs

Reputation: 2569

Since I'm in Python, I can handle the platform specifics manually:

value = 'my/complicated%/string'
quoted_value = '"{}"'.format(value)
if sys.platform.startswith('win32'):
    quoted_value = quoted_value.replace('%', '%%')
    quoted_value = quoted_value.replace('"', '\\"')

Further special characters would complicate this further.

Upvotes: 1

Related Questions