用于创建字符串的 C 宏 [英] C Macros to create strings

查看:16
本文介绍了用于创建字符串的 C 宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

替代标题(帮助搜索)

  • 将预处理器标记转换为字符串
  • 如何从 C 宏的值中生成字符字符串?
  • Convert a preprocessor token to a string
  • How to make a char string from a C macro's value?

原始问题

我想在编译时使用 C #define 来构建文字字符串.

Original Question

I would like to use C #define to build literal strings at compile time.

字符串是为调试、发布等而更改的域.

The string are domains that change for debug, release etc.

我想要一些这样的东西:

I would like to some some thing like this:

#ifdef __TESTING
    #define IV_DOMAIN domain.org            //in house testing
#elif __LIVE_TESTING
    #define IV_DOMAIN test.domain.com       //live testing servers
#else
    #define IV_DOMAIN domain.com            //production
#endif

// Sub-Domain
#define IV_SECURE "secure.IV_DOMAIN"             //secure.domain.org etc
#define IV_MOBILE "m.IV_DOMAIN"

但预处理器不会评估"中的任何内容

But the preprocessor doesn't evaluate anything within ""

  1. 有没有办法解决这个问题?
  2. 这是个好主意吗?

推荐答案

在 C 中,字符串文字是自动连接的.例如,

In C, string literals are concatenated automatically. For example,

const char * s1 = "foo" "bar";
const char * s2 = "foobar";

s1s2 是同一个字符串.

s1 and s2 are the same string.

因此,对于您的问题,答案(不粘贴令牌)是

So, for your problem, the answer (without token pasting) is

#ifdef __TESTING
    #define IV_DOMAIN "domain.org"
#elif __LIVE_TESTING
    #define IV_DOMAIN "test.domain.com"
#else
    #define IV_DOMAIN "domain.com"
#endif

#define IV_SECURE "secure." IV_DOMAIN
#define IV_MOBILE "m." IV_DOMAIN

这篇关于用于创建字符串的 C 宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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