是否有一种干净的可移植方式来“构建”包含文件名

时间:2015-07-01 17:33:09

标签: c macros include c-preprocessor header-files

许多 C 项目都有长达一英里的“包含”目录列表, C 源文件通常在其include指令中包含棘手的相对路径。当不同目录中的文件(并且可能用于不同目的)具有相同名称时,这有时会导致歧义,并且还可能导致编译速度慢,因为编译器必须搜索每个#include文件的许多位置。

概念上更清晰的方法是为每个项目提供一个指定的#include搜索目录,其中包含一个filepaths.h文件,该文件将为包含文件所在的所有目录定义宏,以便代码中的任何位置然后项目可以说像

#include IO_INCLUDES(serialports.h)
#include IO_INCLUDES(timer.h)
#include FILESYS_INCLUDES(filesystem.h)
#include FILESYS_INCLUDES(dirhandling.h)

可能带引号;可能没有。如果 C #include "string1" "string2"定义为等同于#include "string1string2",那么以这种方式处理包含文件路径会很容易,但它不会(在这种情况下,宏可以接受)用引号括起来的参数,宏可以简单地在引号中添加合适的路径名,但它不会。

几乎可行的方法是定义如下内容:

... within a filepaths.h file
#define QUOTE(x) #x
#define MQUOTE(x) QUOTE(x)
#define DUP(x) x
#define MAKENAME(file,path) MQUOTE(DUP(file)DUP(path))

#define IO_INCLUDES(name) MAKENAME(d:/shared_libraries/io,name)
#define FILESYS_INCLUDES(name) MAKENAME(d:/shared_libraries/filesys,name)

... within an individual C file
#include IO_INCLUDES(serialport.h)

如果预处理器没有特别识别路径名组件,那么GCC似乎接受了这个具有正确所需语义的。要求项目文件必须存储在名称与任何宏或预处理器可能识别的任何其他内容不匹配的路径中,但这似乎并不合理。

是否有任何安全且可移植的方式允许filepaths.h文件指示应从中检索文件的目录?预处理器接受#include指令中的宏这一事实表明某些此类功能是有意的,但我无法找出使其安全工作的任何方法。有吗?

1 个答案:

答案 0 :(得分:0)

There is not. According to 6.10.2 paragraph 4 of C99, "The method by which a sequence of preprocessing tokens between a < and a > preprocessing token pair or a pair of " characters is combined into a single header name preprocessing token is implementation-defined", so any attempt to do this will be nonportable.

You essentially have two options. If you really want to have no restrictions on directory names at all, then you'll need to use a separate program to do this part of the preprocessing. Make itself would probably be sufficient; something like m4 would be overkill here.

The other option, and the one I recommend, is to just establish a basic naming convention. Make all your macro names be ALL-CAPS and all your directory names be not in all caps. Then include your own headers before any others so you don't need to worry about what other people named their macros, and the problem vanishes.