问题
Is there any expression possible for the syntax to include multiple headers at once, with no need to write the "#include"-expression for each file new?
Like, for example:
#include <stdio.h>, <stdlib.h>, <curses.h>, <string.h> /* Dummy-Expression 1. */
OR
#include <stdio.h> <stdlib.h> <curses.h> <string.h> /* Dummy-Expression 2. */
Question is for C AND C++.
回答1:
No, there is no way to do this. You have to type out (or copy) each #include
to its own line, like this:
#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
#include <string.h>
This applies to both C and C++.
Some of the other answers discuss creating another header file that includes each of these, but I'm not going to discuss doing that. It in general is a bad idea and causes issues like namespace pollution and the need to recompile when you change that header file.
回答2:
No, there is not.
Write an #include
directive for each inclusion operation you wish to perform.
You could, however, have a "utility" header that does nothing but include many other headers that you use frequently. Then you just include that one utility header. Whether this is a good idea or not, is a matter of opinion.
If you go down that route, don't be tempted to start relying on internal implementation headers.
回答3:
You can make a header file with all the common includes and include that in your files:
File common.h
:
#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
#include <string.h>
and in your file you can include that file instead:
#include <common.h>
回答4:
There's no syntax for that. But if you really want something like that, then just create a new header that contains nothing but multiple #include
statements for the headers you want and then #include "combo-header.h"
whenever needed.
I'd discourage this though. Better to only include what you use explicitly where you use it - for several reasons; compile time and namespace pollution being the top ones.
回答5:
It can be done with a help of auxillary header including header:
#define HEADERS (<stdio.h>)(<stdlib.h>)(<curses.h>)(<string.h>)
#include "Headers.inl"
Where Headers.inl
performs include for each item in HEADERS
sequence:
// Headers.inl
#include <boost/preprocessor/seq.hpp>
#if(0 < BOOST_PP_SEQ_SIZE(HEADERS))
#include BOOST_PP_SEQ_ELEM(0, HEADERS)
#endif
#if(1 < BOOST_PP_SEQ_SIZE(HEADERS))
#include BOOST_PP_SEQ_ELEM(1, HEADERS)
#endif
#if(2 < BOOST_PP_SEQ_SIZE(HEADERS))
#include BOOST_PP_SEQ_ELEM(2, HEADERS)
#endif
#if(3 < BOOST_PP_SEQ_SIZE(HEADERS))
#include BOOST_PP_SEQ_ELEM(3, HEADERS)
#endif
…
It can probably be simplified by letting boost preprocessor handle the all the repetition with BOOST_PP_SEQ_POP_FRONT
and recursive include of itself.
来源:https://stackoverflow.com/questions/58354443/include-multiple-header-files-at-once-with-only-one-include-expression