I want to define a macro which includes another header file like so:
#define MY_MACRO (text) #include "__FILE__##_inline.inl"
So that when the preprocessor parses file person.h, MY_MACRO(blahblah) expands to
#include "person.h.inline.inl"
any hints on how to do this ?
It's not possible to use #define to construct other preprocessor directives, unless you run the preprocessor twice.
But in your case even running the preprocessor twice won't help because the #include must be a single string of the form "..." or <...>.
You cannot use __FILE__ because that is already quoted, and #include doesn't support string concatenation. But you can use macros after #include:
#define STRINGIZE_AUX(a) #a
#define STRINGIZE(a) STRINGIZE_AUX(a)
#define CAT_AUX(a, b) a##b
#define CAT(a, b) CAT_AUX(a, b)
#define MY_MACRO(file, name) STRINGIZE(CAT(file, CAT(name, _inline.inl)))
#include MY_MACRO(aaaa, qqq)
You should use the equivalent Boost.Preprocessor macros instead of CAT and STRINGIZE to prevent global namespace pollution.
You can't write other pre-processor directives using the pre-processor. However, I believe you could define just the file name:
#define MY_MACRO(name) "__FILE__##name_inline.inl"
#include MY_MACRO(name)
The pre-processor runs multiple times until there are no further substitutions it can make, so it should expand the name first and then #include the referenced file.
EDIT: I just tried it and the pre-processor can't handle the quotes like that.
#define MY_MACRO(x) <__FILE__##x_inline.inl>
#include MY_MACRO(foo)
works OK, but <> may not be what you wanted.
EDIT2: As pointed out by sth in comments, the __FILE__ does not expand correctly, which makes this probably not what you want after all. Sorry.
#if 0 /*Windows*/
#define MKDIR_ENABLER <direct.h>
#define MY_MKDIR(x,y) _mkdir((x))
#else /*Linux*/
#define MKDIR_ENABLER <sys/stat.h>
#define MY_MKDIR(x,y) mkdir((x),(y))
#endif
#include MKDIR_ENABLER
int main(void)
{
MY_MKDIR("more_bla",0644);
return 0;
}
This code includes the appropriate header file for mkdir (because it's different on UNIX and Windows) and introduces a nice wrapper for it.
Related
Is there a way to define a macro that contains a #include
directive in its body?
If I just put
the "#include", it gives the error
C2162: "expected macro formal parameter"
since here I am not using # to concatenate strings.
If I use "\# include", then I receive the following two errors:
error C2017: illegal escape sequence
error C2121: '#' : invalid character : possibly the result of a macro expansion
Any help?
So like the others say, no, you can't have #include statements inside a macro, since the preprocessor only does one pass. However, you can make the preprocessor do basically the same thing with a gnarly trick I found myself using recently.
Realise that preprocessor directives won't do anything inside a macro, however they WILL do something in a file. So, you can stick a block of code you want to mutate into a file, thinking of it like a macro definition (with pieces that can be altered by other macros), and then #include this pseudo-macro file in various places (make sure it has no include guards!). It doesn't behave exactly like a macro would, but it can achieve some pretty macro-like results, since #include basically just dumps the contents of one file into another.
For example, consider including lots of similarly named headers that come in groups. It is tedious to write them all out, or perhaps even they are auto-generated. You can partially automate their inclusion by doing something like this:
Helper macros header:
/* tools.hpp */
#ifndef __TOOLS_HPP__
#def __TOOLS_HPP__
// Macro for adding quotes
#define STRINGIFY(X) STRINGIFY2(X)
#define STRINGIFY2(X) #X
// Macros for concatenating tokens
#define CAT(X,Y) CAT2(X,Y)
#define CAT2(X,Y) X##Y
#define CAT_2 CAT
#define CAT_3(X,Y,Z) CAT(X,CAT(Y,Z))
#define CAT_4(A,X,Y,Z) CAT(A,CAT_3(X,Y,Z))
// etc...
#endif
Pseudo-macro file
/* pseudomacro.hpp */
#include "tools.hpp"
// NO INCLUDE GUARD ON PURPOSE
// Note especially FOO, which we can #define before #include-ing this file,
// in order to alter which files it will in turn #include.
// FOO fulfils the role of "parameter" in this pseudo-macro.
#define INCLUDE_FILE(HEAD,TAIL) STRINGIFY( CAT_3(HEAD,FOO,TAIL) )
#include INCLUDE_FILE(head1,tail1.hpp) // expands to #head1FOOtail1.hpp
#include INCLUDE_FILE(head2,tail2.hpp)
#include INCLUDE_FILE(head3,tail3.hpp)
#include INCLUDE_FILE(head4,tail4.hpp)
// etc..
#undef INCLUDE_FILE
Source file
/* mainfile.cpp */
// Here we automate the including of groups of similarly named files
#define FOO _groupA_
#include "pseudomacro.hpp"
// "expands" to:
// #include "head1_groupA_tail1.hpp"
// #include "head2_groupA_tail2.hpp"
// #include "head3_groupA_tail3.hpp"
// #include "head4_groupA_tail4.hpp"
#undef FOO
#define FOO _groupB_
#include "pseudomacro.hpp"
// "expands" to:
// #include "head1_groupB_tail1.hpp"
// #include "head2_groupB_tail2.hpp"
// #include "head3_groupB_tail3.hpp"
// #include "head4_groupB_tail4.hpp"
#undef FOO
#define FOO _groupC_
#include "pseudomacro.hpp"
#undef FOO
// etc.
These includes could even be in the middle of codes blocks you want to repeat (with FOO altered), as the answer by Bing Jian requests: macro definition containing #include directive
I haven't used this trick extensively, but it gets my job done. It can obviously be extended to have as many "parameters" as needed, and you can run whatever preprocessor commands you like in there, plus generate actual code. You just can't use the stuff it creates as the input into another macro, like you can with normal macros, since you can't stick the include inside a macro. But it can go inside another pseudo-macro :).
Others might have some comments on other limitations, and what could go wrong :).
I will not argue the merits for it, but freetype (www.freetype.org) does the following:
#include FT_FREETYPE_H
where they define FT_FREETYPE_H elsewhere
C and C++ languages explicitly prohibit forming preprocessor directives as the result of macro expansion. This means that you can't include a preprocessor directive into a macro replacement list. And if you try to trick the preprocessor by "building" a new preprocessor directive through concatenation (and tricks like that), the behavior is undefined.
I believe the C/C++ preprocessor only does a single pass over the code, so I don't think that would work. You might be able to get a "#include" to be placed in the code by the macro, but the compiler would choke on it, since it doesn't know what to do with that. For what you're trying to do to work the preprocessor would have to do a second pass over the file in order to pick up the #include.
I also wanted to do this, and here's the reason:
Some header files (notably mpi.h in OpenMPI) work differently if you are compiling in C or C++. I'm linking to a C MPI code from my C++ program. To include the header, I do the usual:
extern "C" {
#include "blah.h"
}
But this doesn't work because __cplusplus is still defined even in C linkage. That means mpi.h, which is included by blah.h, starts defining templates and the compiler dies saying you can't use templates with C linkage.
Hence, what I have to do in blah.h is to replace
#include <mpi.h>
with
#ifdef __cplusplus
#undef __cplusplus
#include <mpi.h>
#define __cplusplus
#else
#include <mpi.h>
#endif
Remarkably it's not just mpi.h that does this pathological thing. Hence, I want to define a macro INCLUDE_AS_C which does the above for the specified file. But I guess that doesn't work.
If anyone can figure out another way of accomplishing this, please let me know.
I think you are all right in that this task seems impossible as I also got from
http://groups.google.com/group/comp.lang.c++/browse_thread/thread/03d20d234539a85c#
No, preprocessor directives in C++
(and C) are not reflective.
Pawel Dziepak
Anyway, the reason behind this attempt is that I am trying to make the following
repeatedly used code snippet as a macro:
void foo(AbstractClass object)
{
switch (object.data_type())
{
case AbstractClass::TYPE_UCHAR :
{
typedef unsigned char PixelType;
#include "snippets/foo.cpp"
}
break;
case AbstractClass::TYPE_UINT:
{
typedef unsigned int PixelType;
#include "snippets/foo.cpp"
}
break;
default:
break;
}
}
For another task, I need to have a similar function
void bar(AbstractClass object)
where I will place
#include "snippets/bar.cpp"
and of course it is in "snippets/foo.cpp" and "snippets/bar.cpp" that the task-specific code is written.
I have no idea what you are actually trying to do but it looks like what you might want is a templated function.
That way the PixelType is just a template parameter to the block of code.
Why would the macro need to have an #include? if you're #include'ing whatever file the macro is in, you could just put the #include above the macro with all the rest of the #include statements, and everything should be nice and dandy.
I see no reason to have the macro include anything that couldn't just be included in the file.
Contagious is right -- if you're doing:
myFile.c:
#include "standardAppDefs.h"
#myStandardIncludeMacro
standardAppDefs.h:
#define myStandardIncludeMacro #include <foo.h>
Why not just say:
myFile.c:
#include "standardAppDefs.h"
standardAppDefs.h:
#include <foo.h>
And forget the macros?
I was trying to read a file in compile time. My code is as below
#define STR(x) #x
const char *fileContent = STR(
#include "config.txt"
);
The content of config.txt is
ABC
DEF
What my expected value of fileContent is
ABC
DEF
but I got the
#include "config.txt"
for fileContent.
It seems the order of replacing symbol in visual c++ is #define then #include.
Can I change the order to #include then #define ?
Or any suggestion for reading file to char* in compile time ?
#include is a preprocessor directive.
#define is also a preprocessor directive.
You can't embed one inside the other. Tokens inside a macro argument don't get interpreted as further preprocessor directives. This has little to do with "order" and more about nesting.
You can't just bung an #include in a string literal, either, but there are ways to get what you want.
This may get easier in future versions of C++, if the std::embed proposal gets its way.
In some large C++ projects, there are many #include directives. For example,
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
I have to write four #include in this example. I am so lazy that I only want to write it once. Perhaps like this:
#include {
<iostream>
<boost/asio.hpp>
<boost/bind.hpp>
<boost/date_time/posix_time/posix_time.hpp>
}
Is there any way to do it like this? Or can we define a macro to do this?
Is there any way to do it like this?
No.
The best you could do is put all your #include directives into a dedicated header file, and then #include that single header everywhere it's needed.
You can't do that, because #include uses preprocessor, and preprocessor is dumb as rock.
You could, however, write your own additional preprocessor that takes *.cpp file as input and converts your extended #include syntax into standard syntax. Example of preprocessor is moc
Or you could put all includes into single file, but that'll add unnecessary dependencies and in the long run will increase compilation times.
Personally, I wouldn't bother.
Copy/paste means duplicating
Duplicating code (function bodies, for example) is bad. However, #include directive is not technically a code.
One solution would be to put all those in a file "files_to_be_included.h"
files_to_be_included.h
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
and then using
#include "files_to_be_included.h"
to include them all at once
Here is a macro that you could use (I wouldn't want to though, it made a nice little exercise on writing macros though):
#define HASH #
#define F(X) X
#define INCLUDE(X) F(HASH)include <X>
#define FEI_1(X, ...) INCLUDE(X)
#define FEI_2(X, ...) INCLUDE(X) NEW_LINE FEI_1(__VA_ARGS__)
#define FEI_3(X, ...) INCLUDE(X) NEW_LINE FEI_2(__VA_ARGS__)
#define FEI_4(X, ...) INCLUDE(X) NEW_LINE FEI_3(__VA_ARGS__)
#define FEI_5(X, ...) INCLUDE(X) NEW_LINE FEI_4(__VA_ARGS__)
#define FEI_6(X, ...) INCLUDE(X) NEW_LINE FEI_5(__VA_ARGS__)
#define FEI_7(X, ...) INCLUDE(X) NEW_LINE FEI_6(__VA_ARGS__)
#define FEI_8(X, ...) INCLUDE(X) NEW_LINE FEI_7(__VA_ARGS__)
#define INCLUDE_BLOCK_(_1,_2,_3,_4,_5,_6,_7,_8,NAME,...) NAME
#define INCLUDE_BLOCK(...) INCLUDE_BLOCK_(__VA_ARGS__, \
FEI_8,FEI_7,FEI_6,FEI_5,FEI_4,FEI_3,FEI_2,FEI_1)(__VA_ARGS__)
If you stick this in a header file header_header, then you will be able to use it as follows:
#include <header_header>
INCLUDE_BLOCK(
iostream,
boost/asio.hpp,
boost/bind.hpp,
boost/date_time/posix_time/posix_time.hpp)
/* Write Some Code Here */
This solution is not all that practical, in order to compile your code you now need to run the preprocessing stage twice and insert the NEW_LINE characters.
gcc -E main.cpp -o main.e.cpp
sed -i 's/NEW_LINE/\n/g' main.e.cpp
g++ main.e.cpp -o a.out
It would be possible to extend this code to create a specific boost include block that removes the need to keep adding the boost part. One limit on this current implementation is that you can only include 8 headers.
Some IDE/text editor have custom code snippets.
Check if you have a plug-in for your tool.
What problems could I get when defining NOMINMAX before anything else in my program?
As far as I know, this will make <Windows.h> not define the min and max macros such that many conflicts with the STL, e.g. std::min(), std::max(), or std::numeric_limits<T>::min() are resolved.
Am I right in the assumption that only Windows-specific and legacy code will have problems?
Almost all libraries should not depend on min() and max() defined as macros?
Edit: Will there be be problems with other Windows headers?
Using NOMINMAX is the only not-completely-evil way to include <windows.h>. You should also define UNICODE and STRICT. Although the latter is defined by default by modern implementations.
You can however run into problems with Microsoft’s headers, e.g. for GdiPlus. I’m not aware of problems with headers from any other companies or persons.
If the header defines a namespace, as GdiPlus does, then one fix is to create a wrapper for the relevant header, where you include <algorithm>, and inside the header’s namespace, using namespace std; (or alternatively using std::min; and using std::max):
#define NOMINMAX
#include <algorithm>
namespace Gdiplus
{
using std::min;
using std::max;
}
Note that that is very different from a using namespace std; at global scope in header, which one should never do.
I don’t know of any good workaround for the case where there's no namespace, but happily I haven’t run into that, so in practice that particular problem is probably moot.
I generally use NOMINMAX like this to limit the potential side effects:
#define NOMINMAX
#include <windows.h>
#undef NOMINMAX
That way the scope of the NOMINMAX is relatively confined.
It's not a perfect solution. If something else has already defined NOMINMAX, this pattern fails (though I've never encountered such a case).
If you want to be really, really careful, then you can #include a wrapper header wherever you would have #included windows.h. The wrapper would go something like this:
/* Include this file instead of including <windows.h> directly. */
#ifdef NOMINMAX
#include <windows.h>
#else
#define NOMINMAX
#include <windows.h>
#undef NOMINMAX
#endif
You could imagine doing other things in the wrapper, too, like enforcing UNICODE and/or STRICT.
For precompiled header (like stdafx.h) I use this:
#define NOMINMAX
#include <algorithm>
#include <Windows.h>
#ifndef min
#define min(x,y) ((x) < (y) ? (x) : (y))
#endif
#ifndef max
#define max(x,y) ((x) > (y) ? (x) : (y))
#endif
#include <gdiplus.h>
#undef min
#undef max
I got fix issue by declaring the headers and namespaces in the following order:
#include <windows.h>
#include <minmax.h>
#include <gdiplus.h>
using namespace Gdiplus;
using namespace std;
Is there a way to define a macro that contains a #include
directive in its body?
If I just put
the "#include", it gives the error
C2162: "expected macro formal parameter"
since here I am not using # to concatenate strings.
If I use "\# include", then I receive the following two errors:
error C2017: illegal escape sequence
error C2121: '#' : invalid character : possibly the result of a macro expansion
Any help?
So like the others say, no, you can't have #include statements inside a macro, since the preprocessor only does one pass. However, you can make the preprocessor do basically the same thing with a gnarly trick I found myself using recently.
Realise that preprocessor directives won't do anything inside a macro, however they WILL do something in a file. So, you can stick a block of code you want to mutate into a file, thinking of it like a macro definition (with pieces that can be altered by other macros), and then #include this pseudo-macro file in various places (make sure it has no include guards!). It doesn't behave exactly like a macro would, but it can achieve some pretty macro-like results, since #include basically just dumps the contents of one file into another.
For example, consider including lots of similarly named headers that come in groups. It is tedious to write them all out, or perhaps even they are auto-generated. You can partially automate their inclusion by doing something like this:
Helper macros header:
/* tools.hpp */
#ifndef __TOOLS_HPP__
#def __TOOLS_HPP__
// Macro for adding quotes
#define STRINGIFY(X) STRINGIFY2(X)
#define STRINGIFY2(X) #X
// Macros for concatenating tokens
#define CAT(X,Y) CAT2(X,Y)
#define CAT2(X,Y) X##Y
#define CAT_2 CAT
#define CAT_3(X,Y,Z) CAT(X,CAT(Y,Z))
#define CAT_4(A,X,Y,Z) CAT(A,CAT_3(X,Y,Z))
// etc...
#endif
Pseudo-macro file
/* pseudomacro.hpp */
#include "tools.hpp"
// NO INCLUDE GUARD ON PURPOSE
// Note especially FOO, which we can #define before #include-ing this file,
// in order to alter which files it will in turn #include.
// FOO fulfils the role of "parameter" in this pseudo-macro.
#define INCLUDE_FILE(HEAD,TAIL) STRINGIFY( CAT_3(HEAD,FOO,TAIL) )
#include INCLUDE_FILE(head1,tail1.hpp) // expands to #head1FOOtail1.hpp
#include INCLUDE_FILE(head2,tail2.hpp)
#include INCLUDE_FILE(head3,tail3.hpp)
#include INCLUDE_FILE(head4,tail4.hpp)
// etc..
#undef INCLUDE_FILE
Source file
/* mainfile.cpp */
// Here we automate the including of groups of similarly named files
#define FOO _groupA_
#include "pseudomacro.hpp"
// "expands" to:
// #include "head1_groupA_tail1.hpp"
// #include "head2_groupA_tail2.hpp"
// #include "head3_groupA_tail3.hpp"
// #include "head4_groupA_tail4.hpp"
#undef FOO
#define FOO _groupB_
#include "pseudomacro.hpp"
// "expands" to:
// #include "head1_groupB_tail1.hpp"
// #include "head2_groupB_tail2.hpp"
// #include "head3_groupB_tail3.hpp"
// #include "head4_groupB_tail4.hpp"
#undef FOO
#define FOO _groupC_
#include "pseudomacro.hpp"
#undef FOO
// etc.
These includes could even be in the middle of codes blocks you want to repeat (with FOO altered), as the answer by Bing Jian requests: macro definition containing #include directive
I haven't used this trick extensively, but it gets my job done. It can obviously be extended to have as many "parameters" as needed, and you can run whatever preprocessor commands you like in there, plus generate actual code. You just can't use the stuff it creates as the input into another macro, like you can with normal macros, since you can't stick the include inside a macro. But it can go inside another pseudo-macro :).
Others might have some comments on other limitations, and what could go wrong :).
I will not argue the merits for it, but freetype (www.freetype.org) does the following:
#include FT_FREETYPE_H
where they define FT_FREETYPE_H elsewhere
C and C++ languages explicitly prohibit forming preprocessor directives as the result of macro expansion. This means that you can't include a preprocessor directive into a macro replacement list. And if you try to trick the preprocessor by "building" a new preprocessor directive through concatenation (and tricks like that), the behavior is undefined.
I believe the C/C++ preprocessor only does a single pass over the code, so I don't think that would work. You might be able to get a "#include" to be placed in the code by the macro, but the compiler would choke on it, since it doesn't know what to do with that. For what you're trying to do to work the preprocessor would have to do a second pass over the file in order to pick up the #include.
I also wanted to do this, and here's the reason:
Some header files (notably mpi.h in OpenMPI) work differently if you are compiling in C or C++. I'm linking to a C MPI code from my C++ program. To include the header, I do the usual:
extern "C" {
#include "blah.h"
}
But this doesn't work because __cplusplus is still defined even in C linkage. That means mpi.h, which is included by blah.h, starts defining templates and the compiler dies saying you can't use templates with C linkage.
Hence, what I have to do in blah.h is to replace
#include <mpi.h>
with
#ifdef __cplusplus
#undef __cplusplus
#include <mpi.h>
#define __cplusplus
#else
#include <mpi.h>
#endif
Remarkably it's not just mpi.h that does this pathological thing. Hence, I want to define a macro INCLUDE_AS_C which does the above for the specified file. But I guess that doesn't work.
If anyone can figure out another way of accomplishing this, please let me know.
I think you are all right in that this task seems impossible as I also got from
http://groups.google.com/group/comp.lang.c++/browse_thread/thread/03d20d234539a85c#
No, preprocessor directives in C++
(and C) are not reflective.
Pawel Dziepak
Anyway, the reason behind this attempt is that I am trying to make the following
repeatedly used code snippet as a macro:
void foo(AbstractClass object)
{
switch (object.data_type())
{
case AbstractClass::TYPE_UCHAR :
{
typedef unsigned char PixelType;
#include "snippets/foo.cpp"
}
break;
case AbstractClass::TYPE_UINT:
{
typedef unsigned int PixelType;
#include "snippets/foo.cpp"
}
break;
default:
break;
}
}
For another task, I need to have a similar function
void bar(AbstractClass object)
where I will place
#include "snippets/bar.cpp"
and of course it is in "snippets/foo.cpp" and "snippets/bar.cpp" that the task-specific code is written.
I have no idea what you are actually trying to do but it looks like what you might want is a templated function.
That way the PixelType is just a template parameter to the block of code.
Why would the macro need to have an #include? if you're #include'ing whatever file the macro is in, you could just put the #include above the macro with all the rest of the #include statements, and everything should be nice and dandy.
I see no reason to have the macro include anything that couldn't just be included in the file.
Contagious is right -- if you're doing:
myFile.c:
#include "standardAppDefs.h"
#myStandardIncludeMacro
standardAppDefs.h:
#define myStandardIncludeMacro #include <foo.h>
Why not just say:
myFile.c:
#include "standardAppDefs.h"
standardAppDefs.h:
#include <foo.h>
And forget the macros?