简体   繁体   English

如何在预处理程序时附加到__FILE__并包括结果

[英]how to append to __FILE__ at preprocessor time and include the result

I want to include component.h.gen from component.h . 我想包括component.h.gencomponent.h

I've already seen that I can use __FILE__ with #include and that results in recursive inclusion if there is no header guard. 我已经看到我可以将__FILE__#include一起使用,并且如果没有标题保护,则会导致递归包含。

Is there a way to append a C string literal and include the result? 有没有办法附加C字符串文字并包含结果? This is what I've tried so far: 到目前为止,这是我尝试过的:

#define CAT_IMPL(s1, s2) s1##s2
#define CAT(s1, s2) CAT_IMPL(s1, s2)
#define DO_IT CAT(__FILE__, ".gen")

#include DO_IT

But this results in the same recursion with the file including itself - the ".gen" part is not used - and I get this warning with MSVC: 但这会导致包括文件本身在内的文件具有相同的递归- ".gen"部分未使用-我在MSVC中收到以下警告:

warning C4067: unexpected tokens following preprocessor directive - expected a newline 警告C4067:预处理指令后出现意外的标记-预期换行

Is there a solution that would work with gcc/clang/msvc? 有没有可以与gcc / clang / msvc一起使用的解决方案?

Note that I'm planning on using this in hundreds if not thousands of files and I would like to simplify my life by just copy-pasting the same code - that's why I'm trying to get this to work. 请注意,我打算在数百个(甚至数千个)文件中使用它,并且我想通过复制粘贴相同的代码来简化我的工作,这就是为什么我要使其正常工作。

Unfortunately, this is not possible: 不幸的是,这是不可能的:

  • __FILE__ expands to a string; __FILE__扩展为字符串; you cannot unstringify a string. 您不能取消字符串的字符串化。 So the technique of just adding the "rest" of the string, then stringifying the result, isn't available. 因此,仅添加字符串的“其余”然后对结果进行字符串化的技术不可用。
  • Pasting two string tokens does not create a valid token. 粘贴两个字符串标记不会创建有效的标记。 So pasting isn't available. 因此无法粘贴。
  • String literal concatenation doesn't exist for the preprocessor (preprocessor is translation phase 4; string literal concatenation is phase 6). 预处理程序不存在字符串文字串联(预处理器是转换阶段4;字符串文字串联是阶段6)。

Kind of obscure, but seems to be possible with gcc. 有点晦涩难懂,但似乎可以用gcc实现。

Look at the second answer of this question: 看这个问题的第二个答案:

C Macro - Dynamic #include C宏-动态#include

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM