Hide macros from other headers - c++

Suppose I have this:
// test.h
namespace test {
#define TEST_DEBUG !NDEBUG
class TestClass {
#if TEST_DEBUG
// ...
#endif
};
}
The problem is that other files that include test.h will also get the TEST_DEBUG macro, which is not ideal.
If I use #undef at the end of the header, then that means I can't use the macro in test.cpp.
What would be the best way to solve this issue?

Although I'd advise avoiding macros in C++ (eg this could be replaced with a bool parameter to the function), the simplest way to achieve this is to define TEST_DEBUG in test.cpp before including test.h, and removing it from test.h.
A #include directive is replaced by the c preprocessor similar to a "copy the contents of that file here" way. This copy is repeated each time the #include appears. This also means if there's something defined before the #include appears in one file, but that's not defined in another, then things may break in unpredictable ways (because eg one file thinks an object is bigger than another file thinks it is).
However, to give more idiomatic c++, for a compile time flag you can use bool constexprs. Alternatively, for a runtime change, if it's a class, pass a bool to the constructor to indicate the difference, a function can have an extra parameter that defaults to false, etc.

Related

Which of these two is the proper way to implement a header?

Should you include #include the header of your function declaration in the source file where you define the function?
I've tried both and it seems to work either way. I was wondering if either way is preferred or if one might cause an error in a different compiler
//header.h
#ifndef HEADER_H
#define HEADER_H
int squareVal (int);
#endif
//squareVal.cpp
//should I #include "header.h" here as well?
int squareVal (int val){
return (val*val);
}
//main.cpp
#include"header.h"
using namespace std;
int main(){
cout << squareVal(2) << endl;
}
Both ways seem to work. From my testing and research it sounds like the linker is able to find squareVal.cpp regardless of including the header in that file or not.
Use the #include directive. Put it at the top, in front of any other #include directives. That way, if there's a mistake in the header, the compiler will be more likely to find it. In particular, if you declare the function differently from the way you define it, the compiler will notice. If you don't pull in the header, translation units that use that header will see a different signature from the one that's been defined, and you'll get errors when you try to link. It's much easier when you see the problem early.
Whether it makes a difference, depends on the contents of the header.
In this specific case, because a function definition does not require a previous function declaration, the #include in squareVal.cpp is not (and never will be) necessary.
However, imagine if the header contained more than the function declaration? What if it defined some types needed by the function? What if it defined some constants needed by the function definition? Then you'd need an #include.
It is considered good practice to #include regardless, because then you do not need to think about this, and doing so is effectively free.
The compiler simply puts the WHOLE code from the header right where you insert the #include "header.h". So in this example, the declaration is before the definition of the function and it does nothing bad.

How to avoid long compilation time for #define in common header

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"

Structs inside #define in C++

Being pretty new to C++, I don't quite understand some instructions I encounter such as:
#ifndef BOT_H_
#define BOT_H_
#include "State.h"
/*
This struct represents your bot in the game of Ants
*/
struct Bot
{
State state;
Bot();
void playGame(); //plays a single game of Ants
void makeMoves(); //makes moves for a single turn
void endTurn(); //indicates to the engine that it has made its moves
};
#endif //BOT_H_
What I don't understand is the "#ifndef BOT_H_" and the "#define -- #endif"
From what I gather, it defines a constant BOT_H_ if it's not already defined when the precompiler looks at it. I don't actually get how the struct inside it is a constant and how it is going to let me access the functions inside it.
I also don't see why we're doing it this way? I used C++ a while back and I wasn't using .h files, so it might be something easy I'm missing.
This is known as an include guard, to prevent the contents of a header file from being #included more than once.
That is, it prevents the contents of the header file from being copied into the file that #includes it when it has already #included it before.
The #define isn't defining a constant for the struct, but it's simply defining a constant with no value. If that constant was previously defined, the struct will not be redeclared.
It's called "include guard". It protects you from redefinitions occuring when a header is included more than once. There's also non-standard #pragma once that does the same thing, but might not be supported everywhere.
It does not define a constant whose value is the struct. It defines a constant with an empty value.
It's there so that the content of the header is not included twice. Basically it says something like:
if (!bot_h_included)
{
bot_h_included = true;
// code from the header
}
this is called a header guard it stops the compiler compiling or including the code more than once it is similar to pragma once
Just a side note, I don't recommend using #pragma once I see it a lot in a MVC compatible compilers but just a couple of weeks ago I was working with HP UX and the HP-CC does not support #pragma once, I strongly recommend using #ifndef/#define combinations.

File Local Define

This question more falls into the category of best practices, and clean/safe code for distribution.
I'm working on a math library in C++, for my portfolio, and to use during my last two semesters of College. I want this library to be very easy to use, and to minimize the possibilities of conflicts with pre existing code.
For readability I'm defining TEMP_T as a template for a class, at the top of each of my header files (math/matrix/vec/quaternion). It looks like the following:
#ifdef TEMP_T
#define UNDEF_TEMP_T TEMP_T // Used to reset any other definitions later.
#endif // TEMP_T
#define TEMP_T template<class T> // Used to make the code more readable.
Later on, at the end of the file, I reset the pre existing definition, if nessicary with the following:
#undef TEMP_T // Get rid of our definition.
#ifdef UNDEF_TEMP_T
#define TEMP_T UNDEF_TEMP_T // Reset the previous definition, if it existed.
#undef UNDEF_TEMP_T
#endif // UNDEF_TEMP_T
My question: Would this successfully create a define visible to the file, and the file alone? If so, is this how you would go about accomplishing such a thing? If not, would you be so kind as to give me some insight on your rational behind your ways of doing things?
IMO that is much less readable, falls into the class of pre-processor abuse and I would seriously recommend using the actual definition which will make your code more readable by others which is the point of readability.
In my eyes, you reduce readability this way. This would be the way to reduce the number of characters to be typed/read, but it increases the number of needed human-interpretations, too, which is a bad thing.
On top of that, if anyone has defined TEMP_T in their own code, they would loose their definition by including your headers.
// my code.cpp
#define TEMP_T( var, vartype ) myclass<vartype> var( ##var );
#include <yourmathlib.h>
TEMP_T( anint, int ) // breaks. hard to find the real error.
As a consequence you may define a library-specific MYMATHLIB_TEMP_T, which further decreases readability :)
You can just #include the header file where you declared the template from your other header files.
And if you want to make sure that you don't include the same file twice from 2 different files, you can have
#ifndef MYMATHLIB_TEMP_T
#define MYMATHLIB_TEMP_T
// ... template ...
#endif
around the template header file.
you could just define TEMP_T in an header file and use that header in all your code, maybe you can try to test if your header is included by some macro.
But this way of doing things increases the complexity to read your code.
Why not simply put your template class in a namespace? If you stick it in an namespace, you avoid all the nasty macro stuff. namespaces were explicitly designed to allow code units to be isolated form each other without naming conflicts.

c++: Is it possible to #include inside a function body?

I want to include a header file only if a certain function body is called?
Is this possible or recommended in C++?
No.
You've got it a bit wrong; #include is not processed at run-time, at all. It's not possible to #include a file based on a program's execution characteristics; once the program executes its source is fixed (since it's already compiled).
Possible, yes; recommended no, not usually.
#include is process and an early stage of parsing so works in many places with no regard for the language context at the point of the include.
Note that the include will happen regardless of whether the function is called so it probably isn't going to solve the problem that you are trying to solve. The file included will be placed directly inside the function body so the include file would have to be designed to be included at such a point in the source file.
You're obviously biased by higher-level languages, such as Python, in which is possible to do things like:
if ( a ):
from whatever import whatever_I_need
else:
from whatever_else import whatever_I_need
However, in C++ this is evaluated at compile time (well, actually, #include is a preprocessor directive and it is even evaluated before compile time). Putting that inside a block of an if-else construction will only lead to compilation errors. Just take into account that #include is just a way to dump the contents of a file (normally a header (interface) file) into another one that needs its declarations. Very low level. It will be included anyway.
You can #include inside a function body, but this does not mean that the header file is only included when the function body is called.
The content of the header file will be included by the preprocessor at compile time, and thus the code will always be present in the function.
Obviously, the code is only executed when the function is called.
While you can put a #include inside a function body, it is not what you want to do. There is no way to include a header file only if a certain function is called because the include happens before compile time, but the function call happens at runtime.
Okay, the question was a little off the track, but the actual matter is important.
If for a portion of your methods you actually need to depend on a library that most users won't care about, it's perfectly reasonable to be willing to spare them this unneeded dependency.
You can do this by manipulating preprocessor tokens.
/// myClass.h
/// In order to use BigDep, you need to:
/// - define `MYPROJECT_BIGDEP_USE` before included this header
/// - have `<bigdep-install-path>/include` in your include path
/// - link with `libbigdep.so`
class MyClass
{
public:
void foo() const;
#ifdef MYPROJECT_BIGDEP_USE
void bigDep() const;
#endif // MYPROJECT_BIGDEP_USE
};
/// myClass.cpp
#include "blah.h"
#include "bar.h"
#ifdef MYPROJECT_BIGDEP_USE
#include <bigdep.h>
#endif // MYPROJECT_BIGDEP_USE
void MyClass::foo() const { /**/ }
#ifdef MYPROJECT_BIGDEP_USE
void MyClass::bigdep() { /**/ }
#endif // MYPROJECT_BIGDEP_USE
This way, you have to compile mode, depending on whether the symbol MYPROJECT_BIGDEP_USE is defined or not.
On gcc, you can define symbol on the command line using -D like in -DMYPROJECT_BIGDEP_USE. On Visual Studio it's with /D like in /DMYPROJECT_BIGDEP_USE.
Another option for you user is to wrap your header:
// myProjectMyClass.h
#define MYPROJECT_BIGDEP_USE
#include <myClass.h>
And only ever include "myProjectMyClass.h" and never your header directly.
The use of these preprocessor directives is quite common. For example, when installing the cx_Oracle python module, the installer checked for the version of oracle I used from my environment variables and disabled a number of methods that were not available for it directly at compilation time.
In one program, that I need to use in my app (using Qt) there's:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
using namespace PL;
"#"include "res/przypisania_txt.h"
MainWindow w;
w.show();
...
and when I paste the include before main, it won't compile, so i gues You can use INCLUDE inside a function ;)