将字符串宏传递给 C 程序 - 跨平台 [英] Pass string macro into C program - cross-platform

查看:42
本文介绍了将字符串宏传递给 C 程序 - 跨平台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在编译时将字符串值传递给我的 C 程序:

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

-DNAME=value

我知道有两种方法可以做到这一点:此处描述的字符串化:https://gcc.gnu.org/onlinedocs/cpp/Stringification.html

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));

我在这里遇到的问题是字符串中的宏被替换了,所以当我的字符串包含 -linux- 时,它在 linux 上变成了 -1-.

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

另一种方法是在传递时尝试正确引用字符串.我从 Python setup.py 文件中执行此操作,如下所示:

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"')]

或等效

-DNAME='"value"'

那我就

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

但我找不到在 Linux (gcc) 和 Windows (MSVC 9 for Python 2.7) 上都正确执行此操作的方法.

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.

让我们把它带回 setup.py,这是它需要工作的地方.

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

推荐答案

由于我使用 Python,我可以手动处理平台细节:

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.

这篇关于将字符串宏传递给 C 程序 - 跨平台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆