Passing variables to #include through #define
Is it possible to do something along these lines:
#define import_and_other(s)\
something\
#include s
Such that:
import_and_other("file.h")
becomes:
something
#include "file.h"
Basically, there are certain files that always need the same action taken before they are included, so I want to wrap up #include to perfor开发者_StackOverflow中文版m these actions.
No!
The C99 standard says (section 6.10.2):
A preprocessing directive of the form
# include pp-tokens new-line
(that does not match one of the two previous forms) is permitted. The preprocessing tokens after include in the directive are processed just as in normal text. (Each identifier currently defined as a macro name is replaced by its replacement list of preprocessing tokens.) The directive resulting after all replacements shall match one of the two previous forms.
However, there is another rule (section 10.6.3.2, on 'The # Operator') which says:
Each # preprocessing token in the replacement list for a function-like macro shall be followed by a parameter as the next preprocessing token in the replacement list.
The '#include s' in the macro expansion fails this constraint - the word 'include' is not a parameter to the macro-like function.
This prevents you from generating a (usable) '#include' directive. In any case, during macro expansion, there is another rule (section 10.6.3.4) which says:
The resulting completely macro-replaced preprocessing token sequence is not processed as a preprocessing directive even if it resembles one.
This means that you cannot generate any preprocessor directive from the result of a macro expansion.
Your effort is, sadly, doomed to failure.
No, but you can make your own include file that does both, and then #include it. Name your header file with the import_and_other name of your choice. The #define replacement text is note REALLY multi-line, it just is wrapped for your benefit.
I doubt it. But can achieve the same by including another file and do what ever you want in that file. This will achieve what you are trying to do.
精彩评论