macro definition containing #include directive - c++

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?

Related

Macro for including headers [duplicate]

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?

Can you use #define to change a #include?

Is it possible to change the library included using #include <foo> or #include "foo" to something different during prepossessing so it would instead act as a different library, for example #include <bar>? I have a library that is not working with the current #include statement in just one context, but works fine elsewhere, so I don't want to change it directly. Would it be possible to use #define to fix this?
There are two ways to do this. The simpler, more obvious way:
#define INCLUDE_FOO
// ...
#ifdef INCLUDE_FOO
#include <foo>
#else
#include <bar>
#endif
And the shorter, but finickier way:
#define FOO_HEADER "foo"
// ...
#include FOO_HEADER
You have to be careful if you use the second way, because the C standard does not fully define the behavior of #include followed by anything which is not either "..." or <...>. It says that the "anything which is not..." is fully macro-expanded, not applying the special tokenization rules for #include lines (e.g. <foo.h> is five tokens, not one)
and then something implementation-defined happens.
If the result of full macro expansion is a single string literal token, all implementations I know about will do what you expect, i.e. they will treat that as if #include "..." had been written, where the ... is the contents of the string literal. (However, the behavior of backslashes within the string literal may be not as you expect. Use only forward slashes for directory separators; that works reliably on Windows as well as elsewhere.)
If the result of full macro expansion is anything else, the behavior is unpredictable and differs not only between implementations, but between point releases of the same implementation. Avoid.
Addendum: If an #include line is written in one of the two typical formats to begin with...
#include "foo"
#include <foo>
... then macro expansion does not happen and cannot be forced to happen. This means you are probably up a creek wrt your desire to avoid changing the third-party header with the problem.
Basically in your cpp file you can define a variable that toggles the behaviour of the include file:
So in a.cpp
#define BAR
#include "myHeader.h"
in "myheader.h:"
#ifdef BAR
#include <bar>
#else
#include <foo>
#endif
There is a good GOTW article on other ways you can use preprocessor macros to toggle behaviour

Code completion still acknowledges macro after undef

I have a bunch of macros defined that only serve a purpose within a small area of a project. I want to undefine them so that they don't pollute the global namespace, but Visual Studio still acknowledges their presence after #undef in other files. IE:
//A.hpp
#define A_MACRO
...
//~A.hpp
#undef A_MACRO
...
//B.hpp
#include "A.hpp"
#include "~A.hpp"
...
//main.cpp
#include "B.hpp"
A_MACRO // <- code completion recognizes this despite it being undefined
// and invalid
Do I just have to deal with this, or is there another way to accomplish what I'm trying to do?
EDIT: It seems Code::Blocks properly erases it beyond #undef, so it has to be something within Visual Studio's settings.
Its a perfectly valid tag.
Consider that somewhere in your code you may want to add:
#ifdef A_MACRO
...
#endif
or even:
#ifndef A_MACRO
...
#endif
Wouldn't it suck if your Intellisense quit working?
The macro label is a valid label in both of these contexts. Whether the macro is currently defined or not.

why headerFileName_H

while I am creating a c++ header file, I declare the header file like;
/*--- Pencere.h ---*/
#ifndef PENCERE_H
#define PENCERE_H
I want to learn that why do I need to write underline.
You don't need to use the underline, it's just a convention to separate the header name and extension. You cannot use the literal . since that's not valid in an identifier so you replace it with an underscore which is valid.
The reason you actually do it is as an include guard. The entire contents of the file are something like:
#ifndef PENCERE_H
#define PENCERE_H
// Your stuff goes here.
#endif
so that, if you accidentally include it twice:
#include "pencere.h"
#include "pencere.h"
you won't get everything in it duplicated. The double inclusions are normally more subtle than that - for example, you may include pax.h and diablo.h in your code and pax.h also includes diablo.h for its purposes:
main.c:
#include "pax.h"
#include "diablo.h"
// Other stuff
pax.h:
#ifndef PAX_H
#define PAX_H
#include "diablo.h"
// Other stuff
#endif
diablo.h:
#ifndef DIABLO_H
#define DIABLO_H
typedef int mytype;
#endif
In this case, if the include guards weren't there you would try to compile the line typedef int mytype; twice in your program. Once for main.c -> pax.h -> diablo.h and again for main.c -> diablo.h.
With the include guards, the pre-processor symbol DIABLO_H is defined when main.c includes diablo.h so the #define and typedef are not processed.
This particular mapping of header files to #define names breaks down in the situation where you have dir1/pax.h and dir2/pax.h since they would both use PAX_H. In that case, you can use a scheme like DIR1_PAX_H and DIR2_PAX_H to solve the problem.
The underline is not necessary, that's just a way to produce a string for the include guard that is unlikely to be produced anywhere else and cause hard to detect problems. Even more, you are free to select any symbol for the include guard as long as it will not be defined anywhere else.
It's because you can't #define PENCERE.H
You can define anything you want, but by using a format of using the filename, replacing . with _ means you shouldn't clash #defines that guard importing the same header file twice.
You don't need to write the underline. All you need is a preprocessor symbol which isn't defined anywhere else. If you like (and/or if you have a Pascal background ;-}) you could just as well say
/*--- Pencere.h ---*/
#ifndef THE_PENCERE_HEADER_FILE_WAS_INCLUDED
#define THE_PENCERE_HEADER_FILE_WAS_INCLUDED

Using #define to include another file in C++/C

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.