I have common code on multiple platforms that relies on a header with certain function names to be #included.
The problem is that the [more or less] same header has different names on each platform. I cannot simply rename the header on any platform as it's a standard #include. What is the recommended way to keep this common?
Macros
#ifdef PLATFORM_A
#include <platformA>
#endif
#ifdef PLATFORM_B
#include <platformB>
#endif
//....
Header Masking
In common code:
#include "common.h"
Platform A's "common.h":
#include <platformA>
Platform B's "common.h":
#include <platformB>
Or something else?
What are the pros/cons associated with each method, and in what instances should I use one over another?
Actually, I'd combine both approaches. Instead of using method A over and over again in your code, making maintenance difficult, you should add one common header for each header which is platform dependent and use it to wrap the platform-specific includes:
common_iostream.hpp:
#ifndef COMMON_IOSTREAM_INC
#define COMMON_IOSTREAM_INC
#ifdef PLATFORM_A
#include <iostream>
#endif
#ifdef PLATFORM_B
#include <iostream.h>
#endif
#endif
That way you have a nice set of common_*.hpp headers and your code is kept clean, plus you don't have it split into different platformA/common.hpp, platformB/common.hpp, etc.
Related
Example:
#ifndef HEADER_h
#define HEADER_h
#endif
Instead of HEADER_h, can I do the following?
#ifndef HEADER
or
#ifndef LIBRARY
or
#ifndef SOMETHING
or
#ifndef ANOTHERTHING
etc.
Header guards are just a convention, a "trick", making use of preprocessor conditions. In using a header guard you are creating a macro with a name, and checking whether that macro was already defined.
There is nothing magical about this macro that binds it to the filename of a header, and as such you can call it whatever you want (within reason).
That doesn't mean that you should write #ifndef URGLEBURGLE, though. You want the name to be useful and unique, otherwise there's not much point.
Typically something like #ifndef [PROJECTNAME]_[FILENAME]_INCLUDED is a good idea.
Yes, you can name the include guard symbol whatever you want, but bear in mind that they are supposed to be unique across headers. You definitely don't want a header
// first.h
#ifndef NON_UNIQUE_H
#define NON_UNIQUE_H
void foo();
#endif
and another one
// second.h
#ifndef NON_UNIQUE_H
#define NON_UNIQUE_H
void bar();
#endif
When you include both in one translation unit, one will "win" and its declarations will be visible, e.g.
// main.cpp
#include "first.h" // now, NON_UNIQUE_H is defined
#include "second.h" // NON_UNIQUE_H already there, doesn't do anything
int main(int, char**)
{
bar(); // error, won't compile, bar() isn't declared
}
Besides the necessity to circumvent such scenarios, it's best to stick to some convention throughout your project. One classical way of doing it is to convert the header file base name to upper case and append _H. If you have header files with the same base name in different directories, you can include the directory name, e.g. SUBDIR_FOO_H and OTHERSUBDIR_FOO_H. But this is up to you.
You can use a construction like
#if !defined(HEADER) || !defined(LIBRARY)
At your question, you are using
#ifndef HEADER_h
#define HEADER_h
#endif
It's the same as "#pragma once"
And yes, you can use different names of defines. In your case, LIBRARY, SOMETHING, HEADER_h - defines, that you can set in code(#define MY_VAR_NAME) or via compiler options(flag -DMY_VAR_NAME).
Your example is a so-called header guard that allows us to ensure the contents of the header are included only once. However, that is not the only use of #ifndef.You can use #ifndef for conditional compilation as in
#ifndef NO_DEBUG
do_some_debug_stuff();
#endif
So it is not only for header guards, but in general you have to carefully choose the name of the symbols you are introducing to prevent they are clashing with symbols defined elsewhere. It is just that header guards are so common that certain conventions exist (eg using FOLDER_FILENAME_H is usually sufficient to ensure uniqueness). And you need to be aware that certain names are reserved (eg starting with two underscores or underscore followed by capital letter).
I was wondering if there is an elegant way to solve this problem. Suppose there's a common header eg
// common.h
#ifndef COMMON_H
#define COMMON_H
#define ENABLE_SOMETHING
//#define ENABLE_SOMETHING_ELSE
#define ENABLE_WHATEVER
// many others
#endif
Now this file is included by, let's say 100 other header files and the various #define are used to enable or disable some parts of code which are confined to just 1-2 files.
Everytime a single #define is changed the whole project seems to be rebuilt (I'm working on Xcode 5.1), which makes sense as it must be literally replaced all around the code and the compiler can't know a priori where it's used.
I'm trying to find a better way to manage this, to avoid long compilation times, as these defines are indeed changed many times. Splitting each define in their corresponding file/files could be a solution but I'd like the practical way to have everything packed together.
So I was wondering if there is a pattern which is usually used to solve this problem, I was thinking about having
// common.h
class Enables
{
static const bool feature;
};
// common..cpp
bool Enables::feature = false;
Will this be semantically equivalent when compiling optimized binary? (eg. code inside false enables will totally disappear).
You have two distinct problems here:
Splitting each define in their corresponding file/files could be a solution but I'd like the practical way to have everything packed together.
This is your first problem. If I undestand correctly, if you have more than one functional area, you are not interested in having to include a header for each of them (but a single header for everything).
Apply these steps:
do split the code by functionality, into different headers; Each header should contain (at most) what was enabled by a single #define FEATURESET (and be completely agnostic to the existence of the FEATURESET macro).
ensure each header is only compiled once (add #pragma once at the beginning of each feature header file)
add a convenience header file that performs #if or #ifdef based on your defined features, and includes the feature files as required:
// parsers.h
// this shouldn't be here: #pragma once
#ifdef PARSEQUUX_SAFE
#include <QuuxSafe.h>
#elif defined PARSEQUUX_FAST
#include <QuuxFast.h>
#else
#include <QuuxSafe.h>
#endif
// eventually configure static/global class factory here
// see explanation below for mentions of class factory
Client code:
#include <parsers.h> // use default Quux parser
#define PARSEQUUX_SAFE
#include <parsers.h> // use safe (but slower) Quux parser
So I was wondering if there is a pattern which is usually used to solve this problem
This is your second problem.
The canonical way to enable functionality by feature in C++, is to define feature API, in terms of base classes, class factories and programming to a generic interface.
// common.h
#pragma once
#include <Quux.h> // base Quux class
struct QuuxFactory
{
enum QuuxType { Simple, Feathered };
static std::unique_ptr<Quux> CreateQuux(int arg);
static QuuxType type;
};
// common.cpp:
#include <common.h>
#include <SimpleQuux.h> // SimpleQuux: public Quux
#include <FeatheredQuux.h> // FeatheredQuux: public Quux
std::unique_ptr<Quux> QuuxFactory::CreateQuux(int arg)
{
switch(type) {
case Simple:
return std::unique_ptr<Quux>{new SimpleQuux{arg}};
case Feathered:
return std::unique_ptr<Quux>{new FeatheredQuux{arg}};
};
// TODO: handle errors
}
Client code:
// configure behavior:
QuuxFactory::type = QuuxFactory::FeatheredQuux;
// ...
auto quux = QuuxFactory::CreateQuux(10); // creates a FeatheredQuux in this case
This has the following advantages:
it is straightforward and uses no macros
it is reusable
it provides an adequate level of abstraction
it uses no macros (as in "at all")
the actual implementations of the hypothetical Quux functionality are only included in one file (as an implementation detail, compiled only once). You can include common.h wherever you want and it will not include SimpleQuux.h and FeatheredQuux.h at all.
As a generic guideline, you should write your code, such that it requires no macros to run. If you do, you will find that any macros you want to add over it, are trivial to add. If instead you rely on macros from the start to define your API, the code will be unusable (or close to unusable) without them.
There is a way to split defines but still use one central configuration header.
main_config.h (it must not have an include guard or #pragma once, because that would cause strange results if main_config.h is included more than once in one compilation unit):
#ifdef USES_SOMETHING
#include "something_config.h"
#endif
#ifdef USES_WHATEVER
#include "whatever_config.h"
#endif
something_config.h (must not have include guards for the same reason as main_config.h):
#define ENABLE_SOMETHING
All source and header files would #include only main_config.h, but before the include they must declare what part of it would they be referring to:
some_source.cpp:
#define USES_SOMETHING
#include "main_config.h"
some_other_file.h:
#define USES_WHATEVER
#include "main_config.h"
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;
If I have multiple class and I want to have them all come under the same namespace and in my project I just want to have one include and that will give me all of the classes how would I go about doing this? I have played around with this but keep hitting a dead end.
Thanks in advance.
If you want only one include, namespaces have nothing to do with this.
You can create a file that only contains #include statements.
Something like this:
//classes file
#include "classA"
#include "classB"
#include "classC"
And the include all of them with only one include
#include "classes"
A real example can be found in the STL.
Take vector for instance:
#ifndef _GLIBCXX_VECTOR
#define _GLIBCXX_VECTOR 1
#pragma GCC system_header
#include <bits/stl_algobase.h>
#include <bits/allocator.h>
#include <bits/stl_construct.h>
#include <bits/stl_uninitialized.h>
#include <bits/stl_vector.h>
#include <bits/stl_bvector.h>
#ifndef _GLIBCXX_EXPORT_TEMPLATE
# include <bits/vector.tcc>
#endif
#ifdef _GLIBCXX_DEBUG
# include <debug/vector>
#endif
#endif /* _GLIBCXX_VECTOR */
You get all of this by just doing #include <vector>
Namespaces and header files are unrelated. If you want to provide a single header file for inclusion you can either go with Tom's advice of adding a 'include-all' header or you can pack all your headers into a single file (this might be a bad idea unless the codebase is really stable, as a change in a single element will force recompiling everything). Anyway you can use different namespaces within the same header:
#ifndef HEADER_GUARD_H_
#define HEADER_GUARD_H_
namespace A {
class TheA {};
}
namespace B {
class TheB {};
}
namespace A { // you can even reopen the namespace
class AnotherA {};
}
#endif
Note that the difference is the packaging: whether you need to ship one or more files... in Tom's answer the preprocessor will generate a file similar to the manually generated header before passing the contents to the compiler.
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?