本文介绍了包括C / C ++头文件不止一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

时它曾经有用包含头文件超过C或C ++?

Is it ever useful to include a header file more than once in C or C++?

如果从未使用的机制,为什么会编译器曾经担心,包括一个文件两次;如果真的是无用的,那岂不是更方便,如果新的编译器确信每头只包括一次?

If the mechanism is never used, why would the compiler ever worry about including a file twice; if it really were useless, wouldn't it be more convenient if newer compilers made sure every header is included only once?

编辑:

据我所知,有做这样的事情并的的,但为什么你应该有指定甚至认为?难道不应该是编译器的默认行为,包括文件只有一次?

I understand that there are standard ways of doing things like include guards and pragma once, but why should you have to specify even that? Shouldn't it be the default behavior of the compiler to include files only once?

推荐答案

是的,它产生的时候用preprocessor ​​code,或者做这样Boost.PP技巧是很有用的一样。

Yes, it's useful when generating code with the preprocessor, or doing tricks like Boost.PP does.

有关的例子,发现X宏。其基本思路是,该文件包含宏的身体,你的#define 的参数,然后的#include 它。这里是一个人为的例子:

For an example, see X Macros. The basic idea is that the file contains the body of the macro and you #define the arguments and then #include it. Here's a contrived example:

macro.xpp

macro.xpp

std::cout << MESSAGE;
#undef MESSAGE

file.cpp:

file.cpp:

int main() {
# define MESSAGE "hello world"
# include "macro.xpp"
}

这也使您可以使用#如果和朋友在争论,一些正常宏不能做的。

This also allows you to use #if and friends on the arguments, something that normal macros can't do.

这篇关于包括C / C ++头文件不止一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 16:11