C预处理程序可以执行简单的字符串操作吗? [英] Can the C preprocessor perform simple string manipulation?

查看:75
本文介绍了C预处理程序可以执行简单的字符串操作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是 C 宏怪异问题.

是否可以编写一个以字符串常量X("...")作为参数并求值相同长度的字符串Y的宏,以使Y的每个字符都是X的相应字符的[常数]算术表达式.

Is it possible to write a macro that takes string constant X ("...") as argument and evaluates to sting Y of same length such that each character of Y is [constant] arithmetic expression of corresponding character of X.

这不可能,对吧?

推荐答案

否,C预处理程序将字符串文字视为单个标记,因此它无法执行任何此类操作.

No, the C preprocessor considers string literals to be a single token and therefore it cannot perform any such manipulation.

您要求的内容应在实际的C代码中完成.如果您担心运行时性能并希望在编译时委派此固定任务,则现代优化的编译器应成功处理此类代码-他们可以展开任何循环并预先计算任何固定表达式,同时占用代码大小和CPU缓存使用量模式,这是预处理器不知道的.

What you are asking for should be done in actual C code. If you are worried about runtime performance and wish to delegate this fixed task at compile time, modern optimising compilers should successfully deal with code like this - they can unroll any loops and pre-compute any fixed expressions, while taking code size and CPU cache use patterns into account, which the preprocessor has no idea about.

另一方面,您可能希望您的代码包含这样的修改后的字符串文字,但不希望或不需要原始字符串,例如您想要使程序解码的文本变得晦涩难懂,并且您不想在可执行文件中包含原始字符串.在这种情况下,您可以使用一些构建系统脚本来执行此操作,例如,使用另一个C程序来生成修改后的字符串,然后在您的实际程序的C编译器命令行中将它们定义为宏.

On the other hand, you may want your code to include such a modified string literal, but do not want or need the original - e.g. you want to have obfuscated text that your program will decode and you do not want to have the original strings in your executable. In that case, you can use some build-system scripting to do that by, for example, using another C program to produce the modified strings and defining them as macros in the C compiler command line for your actual program.

这篇关于C预处理程序可以执行简单的字符串操作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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