Stringify C预处理 [英] Stringify C preprocess

查看:255
本文介绍了Stringify C预处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的第一篇文章,因此,如果我太含糊或提供每个人都可以凭直觉假设的信息,请告诉我.

This is my first post, so if I'm being too vague or giving information that everyone would intuitively assume, please let me know.

我对使用 C 进行写作非常陌生,只是想更好地了解预处理.我正在编写一个简单的程序,该程序可以直接使用gcc -Wall -std=c99 -DSEED=argument从控制台输入参数,其中我的参数应为整数,或者如果未定义-D,则用户将输入它.

I'm very new to writing in C and am just trying to get a better understanding of preprocessing. I'm writing a simple program that can take in arguments either directly from the console using gcc -Wall -std=c99 -DSEED=argument, where my argument should be a an integer, or if the -D is not defined the user will input it.

SEED值仅在srand()中使用.我很困惑,如果我输入-DSEED=a作为参数,为什么我的代码不能编译,而当我输入-DSEED=1时,为什么我的代码不能编译.我收到一个âa"未声明(此函数中的第一个用法)错误,并且真的不明白两者之间的区别.我以为#define将变量类型与输入匹配,因此,如果我输入"a",则#SEED将是一个字符,如果我输入"1",则将#SEED将是一个整数.

The SEED value is simply used in srand(). I'm very confused why my code will not compile if I put in an -DSEED=a as my argument while if I put -DSEED=1 it will compile. I'm getting a "âaâ undeclared (first use in this function)" error and really don't understand the difference between the two. I thought the #define matched up the variable type with the input, so if I put in an "a" #SEED would be a char and if I put in a "1" #SEED would be an int.

如果未定义SEED,那么我正在使用#ifndef SEED命令,并且效果很好. 我认为我应该对输入SEED进行字符串化",然后可以检查它是否为整数.在网上阅读了一些文章后,我尝试使用:

If the SEED is not defined I'm using a #ifndef SEED command and this works well. I think I'm supposed to "stringify" the input SEED and then can check if it is an integer or not. After reading some articles online I'm trying to use:

#ifndef SEED
    //code
#else
    #define TO_STRING( input ) #input
    char c;
    c = TO_STRING( SEED )
    //Then I was going to use c to figure out if it was an int.
#endif

这是行不通的,任何能够指出您认为我可能存在的误解的人都将不胜感激.

This is not working and anyone able to point out any misconceptions that you think that I may have would be greatly appreciated.

编辑-所以我确实弄清楚了为什么尝试-DSEED=a时为什么会收到错误消息,因为它正在将其作为变量读取.

EDIT - So I did figure out why I was receiving the error message when trying the -DSEED=a, because it was reading it as a variable.

推荐答案

要对#define进行字符串化,您需要使用两步方法:

To stringify a #define you need to use a two-step approach:

#define _STRINGIFY(s) #s
#define STRINGIFY(s) _STRINGIFY(s)

...

#define SEED 123

...

const char * pszSeed = STRINGIFY(SEED); /* 'pszSeed' would point to "123" form here on. */

如果您只想使用一个字符,只需通过*pszSeedpszSeed[0]对其进行访问.

If you only want to use one character simply access it via *pszSeed or pszSeed[0].

这篇关于Stringify C预处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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